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);

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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<String, Object> resultMap = new Gson().fromJson(jr, new TypeToken<Map<String, Object>>() { }.getType());
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.