I have a json like the following:
{
"id": "uuid-1111"
"country": "US",
"car_brand": "Ford",
"info": {
"color": "red",
"weight": 70
}
}
I have a Data class:
public class Data implements Serializable {
private Map<String, Object> jsonData;
public Map<String, Object> getJsonData() {
return jsonData;
}
public void setJsonData(Map<String, Object> jsonData) {
this.jsonData = jsonData;
}
}
I parse the json string to a Map<String,Object> with jackson using:
HashMap<String, Object> props = new ObjectMapper().readValue(jsonString, new TypeReference<HashMap<String, Object>>() {
});
// assign it to the jsonData attribute:
Data data = new Data();
data.setJsonData(props);
after that I wanted to access the “info” field of the json (map) and also parse it to a Map<String,Object> like this:
String infoJson = data().getJsonData().get("info").toString();
HashMap<String, Object> props2 = new ObjectMapper().readValue(infoJson, new TypeReference<HashMap<String, Object>>() {});
but this throws JsonProcessingException with message: Unexpected character ('c' (code 99)): was expecting double-quote to start field name
And that is correct because when I log infoJson it looks like (notice it does not have double quotes, belive this happened because it was already mapped earlier) {color=red, weight=70}
So I tried to directly cast to map and it worked:
HashMap<String, Object> props = (HashMap<String, Object>) data.getJsonData().get("info");
but maybe there is another way safer with jackson instead of directly casting, if there is not, how can I make sure I can cast it before trying so I avoid exception? Thanks!