如何在java中将字符串转换为Hashmap

如何在java中将字符串转换为Hashmap,java,collections,hashmap,Java,Collections,Hashmap,如何将字符串转换为哈希映射 String value=“{first_name=naresh,last_name=kumar,gender=male}” 进入 Map={ first_name=naresh, 姓氏=库马尔, 性别=男性 } 其中键为名字,姓氏和性别,值为naresh,kumar,男性 注意:键可以是任何类似city=hydrabad的东西 我正在寻找一种通用的方法 String value = "{first_name = naresh,last_name = kumar,

如何将
字符串
转换为
哈希映射

String value=“{first_name=naresh,last_name=kumar,gender=male}”
进入

Map={
first_name=naresh,
姓氏=库马尔,
性别=男性
}
其中键为
名字
姓氏
性别
,值为
naresh
kumar
男性

注意:键可以是任何类似
city=hydrabad
的东西

我正在寻找一种通用的方法

String value = "{first_name = naresh,last_name = kumar,gender = male}"
让我们开始吧

  • 字符串中删除
    {
    }
    ,first_name=naresh,last_name=kumar,gender=male
  • 字符串
    >3个元素的数组中拆分出来
  • 现在您有了一个
    数组
    3
    元素
  • 迭代
    数组
    并按
    =
  • 创建一张
    地图
    将每个部分用
    =
    隔开。第一部分为
    ,第二部分为

  • 这是一个解决方案。如果要使其更通用,可以使用
    StringUtils

    String value = "{first_name = naresh,last_name = kumar,gender = male}";
    value = value.substring(1, value.length()-1);           //remove curly brackets
    String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
    Map<String,String> map = new HashMap<>();               
    
    for(String pair : keyValuePairs)                        //iterate over the pairs
    {
        String[] entry = pair.split("=");                   //split the pairs to get key and value 
        map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
    }
    

    如果您正在使用
    apache.commons.lang
    包中包含的
    StringUtils

    @Test
    
    @Test
    public void testToStringToMap() {
        Map<String,String> expected = new HashMap<>();
        expected.put("first_name", "naresh");
        expected.put("last_name", "kumar");
        expected.put("gender", "male");
        String mapString = expected.toString();
        Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
                .map(arrayData-> arrayData.split("="))
                .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));
    
        expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
    }
    
    公共无效testToStringToMap(){ Map expected=新的HashMap(); 预期。put(“名字”、“纳雷什”); 预期。put(“姓氏”、“库马尔”); 预期。put(“性别”、“男性”); 字符串mapString=应为.toString(); Map actual=Arrays.stream(mapString.replace(“{,”).replace(“},”).split(“,”) .map(arrayData->arrayData.split(“=”)) .collect(Collectors.toMap(d->((String)d[0]).trim(),d->(String)d[1]); 应为.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())); }
    试试这个:)

    例子 输入:“a=0,b={a=1},c={ew={qw=2},0=a” 输出:{0=a,a=0,b={a=1},c={ew={qw=2}}}

    您可以在一行中完成,用于任何对象类型,而不仅仅是映射。 (因为我的使用非常自由,所以我共享基于Gson的方法)

    Gson-Gson=new-Gson();
    Map attributes=gson.fromJson(gson.toJson(value),Map.class);
    
    它所做的是:

  • gson.toJson(value)
    将把对象序列化为等价的Json表示形式
  • gson.fromJson
    将Json字符串转换为指定的对象。(在本例中-
    Map
  • 这种方法有两个优点:

  • 将对象而不是字符串传递给
    toJson
    方法的灵活性
  • 您可以使用这一行转换为任何对象,甚至您自己声明的对象

  • 应使用此方式转换为地图:

        String student[] = students.split("\\{|}");
        String id_name[] = student[1].split(",");
    
        Map<String,String> studentIdName = new HashMap<>();
    
        for (String std: id_name) {
            String str[] = std.split("=");
            studentIdName.put(str[0],str[1]);
      }
    
    String student[]=students.split(“\\{124}”);
    字符串id_name[]=student[1]。拆分(“,”);
    Map studentIdName=new HashMap();
    用于(字符串标准:id\U名称){
    字符串str[]=std.split(“”);
    studentIdName.put(str[0],str[1]);
    }
    

    从字符串中提取“key,value”对并创建映射。您尝试过什么吗?与逻辑描述相关的问题是非常不鼓励的,因为对于上述及其遥远的主题可能有多种解决方案。顺便问一下,你的方法是什么?你是否尝试了一些东西或在某个地方卡住了?如果我知道确切的键是什么以及有多少键,我们可以帮助这项工作,但如果我有10个字符串键。我尝试使用mapper.readValue(输入,new TypeReference(){})转换相同的键从jackson library但引发的ParseException可能会在调用map.get(trimmedString)@Nareshkumar时修剪字符串以避免混淆。这没有问题。+1用于指示方向,而不是填鸭式地使用逗号进行代码拆分是不对的,如果map={num=“12,122016”,name=blabla}@用户5980143然后你必须想出一个不同的策略。提供完整的答案是扼杀OP的学习机会。这并没有帮助他,而是鼓励OP再次问同样的问题。很抱歉,但我的意图是,如果我不知道字符串中的键是什么,你不必知道键。我的代码总是使用等号的左侧作为键。你试过了吗?如果键或值中有逗号,它就会断开。应该考虑这一点。value = StrugULSL.Sub介于(value,{),“}”之间;当值是JSON STRIGMAP ToStand时,不应考虑按要求使用CAST映射,将MAP ToScript转换为MaPoice不是将这种类型的说明添加到自己的帖子中——请将其添加到您的答案中,和删除注释。最好添加代码解释以改进答案。我不擅长解释请记住,您应该处理这种类型的字符串->“{a={a={a=[a,b,c],b=c},c=0}”
    @Test
    public void testToStringToMap() {
        Map<String,String> expected = new HashMap<>();
        expected.put("first_name", "naresh");
        expected.put("last_name", "kumar");
        expected.put("gender", "male");
        String mapString = expected.toString();
        Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
                .map(arrayData-> arrayData.split("="))
                .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));
    
        expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
    }
    
    public static HashMap HashMapFrom(String s){
        HashMap base = new HashMap(); //result
        int dismiss = 0; //dismiss tracker
        StringBuilder tmpVal = new StringBuilder(); //each val holder
        StringBuilder tmpKey = new StringBuilder(); //each key holder
    
        for (String next:s.split("")){ //each of vale
            if(dismiss==0){ //if not writing value
                if (next.equals("=")) //start writing value
                    dismiss=1; //update tracker
                else
                    tmpKey.append(next); //writing key
            } else {
                if (next.equals("{")) //if it's value so need to dismiss
                    dismiss++;
                else if (next.equals("}")) //value closed so need to focus
                    dismiss--;
                else if (next.equals(",") //declaration ends
                        && dismiss==1) {
                    //by the way you have to create something to correct the type
                    Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
                    base.put(tmpKey.toString(),ObjVal);//declaring
                    tmpKey = new StringBuilder();
                    tmpVal = new StringBuilder();
                    dismiss--;
                    continue; //next :)
                }
                tmpVal.append(next); //writing value
            }
        }
        Object objVal = object.valueOf(tmpVal.toString()); //same as here
        base.put(tmpKey.toString(), objVal); //leftovers
        return base;
    }
    
    Gson gson = new Gson();    
    Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);
    
        String student[] = students.split("\\{|}");
        String id_name[] = student[1].split(",");
    
        Map<String,String> studentIdName = new HashMap<>();
    
        for (String std: id_name) {
            String str[] = std.split("=");
            studentIdName.put(str[0],str[1]);
      }