2

To convert json String to pojo using jackson API can use :

String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}";
User user1 = mapper.readValue(jsonInString, User.class);

This requires that create class User that matches structure of json String.

Using json-simple API can use instead :

JSONObject json = (JSONObject)new JSONParser().parse(jsonInString);

Using json-simple do not need to include a pojo that matches json format. Can similar be used in jackson ? json-simple is less verbose as do not have to create the class that matches json structure.

sactiw
  • 21,935
  • 4
  • 41
  • 28
blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

3

Jackson can deserialize a json String into a general-purpose Map:

Map<String, Object> m  = new ObjectMapper().readValue(jsonInString, Map.class);
for (Map.Entry<String, Object> entry : m.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue() + "(" + entry.getValue().getClass().getName() + ")");
}

output:

age -> 33(java.lang.Integer)
messages -> [msg 1, msg 2](java.util.ArrayList)
name -> mkyong(java.lang.String)
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
2

You can use similar API

JsonNode node = mapper.readTree(jsonInString);