I know it is very easy to use Jackson to convert Map to Json. But I want to know if there is a better way for my situation. Below is my code.
String jsonInfo = "{\"attr\":\"value\",\"attr2\",\"value2\"}";
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","daniel");
map.put("info",mapper.readValue(jsonInfo, new TypeReference<Map>(){}));
String finalJsonString = mapper.writeValueAsString(map);
As you can see, even I already know jsonInfo is a json string. For this part, I convert it into a map then finally let Jackson convert it to json again. Is there any better way that I can avoid such duplicated work?
You just want to use Jackson to parse your JSON into its tree structure where you can then add data. This eliminates the extra step of serializing/deserializing to a POJO (or Map)
Your
finalJsonthen becomes:Note that
JsonNodeis immutable, but can be cast to anObjectNodeif you wanted to modify your original JSON as well.