简体   繁体   中英

Convert nested JSON to HashMap

I have the below String which represents a nested 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. The Object is technically an 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?

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. See More:

Convert json string without quotes into a map

Gson parse unquoted value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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