0

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);
MisterIbbs
  • 247
  • 1
  • 7
  • 20

1 Answers1

0

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

Ronak Jain
  • 3,073
  • 1
  • 11
  • 17
  • Thanks, as values needed quotes I cannot use ObjectMapper. I tried to use GSON instead but then realised it doesnt like values with spaces and throws a MalformedJSONException on the fromJson() function. The below code is what I have so far: JsonReader jr = new JsonReader(new StringReader(jsonString.trim())); jr.setLenient(true); Map resultMap = new Gson().fromJson(jr, new TypeToken>() { }.getType()); – MisterIbbs Jan 06 '23 at 13:56
  • @MisterIbbs Spaces are why quotes are needed, So yeah GSON would try to do as much as possible but unquoted spaces, commas in string will cause trouble – Ronak Jain Jan 06 '23 at 15:43