简体   繁体   English

将嵌套的 JSON 转换为 HashMap

[英]Convert nested JSON to HashMap

I have the below String which represents a nested json:我有以下代表嵌套 json 的字符串:

{ history:{name:[{value:Jim, details:Final}],job:[{value:Builder, details:Pending}]} }

In Java, I would like to convert it to its equivalent HashMap<String, Object> type.在 Java 中,我想将其转换为等效的 HashMap<String, Object> 类型。 The Object is technically an ArraList<Map<String, Object>>. Object 在技术上是一个 ArraList<Map<String, Object>>。 I can get this to work by manually wrapping escaped quotes around the strings like below:我可以通过在字符串周围手动包装转义引号来实现它,如下所示:

{ \"history\":{\"name\":[{\"value\":\"Jim\", \"details\":\"Final\"}]} }

Is there a way to do this formatting automatically via some function. I have tried to use ObjectMapper as below with the string above but it creates an empty Map. Can anyone assist?有没有一种方法可以通过一些 function 自动进行这种格式化。我尝试将 ObjectMapper 与上面的字符串一起使用,但它会创建一个空的 Map。有人可以帮忙吗?

Map<String, Object> map = new ObjectMapper().readValue(jsonString, HashMap.class);

This should work for field names这应该适用于字段名称

ObjectMapper objectMapper = new ObjectMapper();                          
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
Map<String, String> Shop_Details = objectMapper.readValue(jsonString, HashMap.class);

Although, values will still need to have quotes.虽然,值仍然需要有引号。 You can try GSON instead.您可以试试 GSON。 See More:查看更多:

Convert json string without quotes into a map 将不带引号的 json 字符串转换为 map

Gson parse unquoted value Gson 解析不带引号的值

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

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