简体   繁体   English

Jackson ObjectMapper使用Json字符串键反序列化Map

[英]Jackson ObjectMapper deserialize Map with Json string key

The task is create correct Json string representation. 任务是创建正确的Json字符串表示。 There are Map that may contains value that Json string. 有Map可能包含Json字符串的值。 During write this map to string mapper escape new line and quote Json. 在写这个映射到字符串mapper期间转义新行并引用Json。

private String getJson() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, String> map = new HashMap<>();
    map.put("key1", "val1");
    map.put("key2", "val2");
    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
}

return: 返回:

{
  "key1" : "val1",
  "key2" : "val2"
}

Code

public String test() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, String> map = new HashMap<>();
    map.put("information", getJson());
    String result = mapper.writeValueAsString(map);
    System.out.println(result);
    return result; 
}

return 返回

{"information":"{\r\n  \"key1\" : \"val1\",\r\n  \"key2\" : \"val2\"\r\n}"}

But is it possible for test() method return String like: 但是test()方法可以返回String,如:

{
  "information": {
    "key1": "val1",
    "key2": "val2"
  }
}

Thanks 谢谢

Problem in console output. 控制台输出问题。 Map has value as string. Map的值为字符串。 If you want formmating output you can put map with "key1", "key2" in your map with key "information" and call mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map) 如果你想要格式化输出你可以在你的地图中用“key1”,“key2”放置关键字“信息”,并调用mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map)

You have to convert JSON back to map before putting it to "information" map. 在将JSON放入“信息”映射之前,您必须将JSON转换回映射。 In your code it is treated just as a string not a map. 在您的代码中,它被视为字符串而不是地图。 So you have to update your test() method to something like this: 所以你必须将test()方法更新为这样的东西:

public static String test() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {};
    Map<String, String> oldMap = mapper.readValue(getJson(), typeRef);

    Map<String, Map<String, String>> map = new HashMap<>();
    map.put("information", oldMap);

    String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
    System.out.println(result);
    return result; 
}

And the outptut is 而且外面是

{
  "information" : {
    "key1" : "val1",
    "key2" : "val2"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM