1) Use JSONNode with ObjectMapper using mapper.readTree(jsonString)

  • eg: String jsonString = “{“name”:”superman”,”age”:”25″}”;

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode jsonNode1 = rootNode.get(“name”);

example reading from json file:

InputStream inputStream = ExampleStructure.class.
.getResourceAsStream(“example.json”);
JsonNode rootNode = mapper.readTree(inputStream);

//usage of path() in addition to usage of get()

rootNode.path(“address”).path(“country”).textValue();

More detailed example:

2) Use ObjectMapper and mapper.readValue(source_json, destination_pojo);

Screen Shot 2019-01-15 at 12.35.56 AM.png

Screen Shot 2019-01-15 at 12.37.11 AM.png

3) Use JSONObject(source_json) and destination is a  jsonObject.getJsonArray(“nodename”) etc

Screen Shot 2019-01-15 at 12.39.56 AM.png

FAQ )
So
readTree() for JSONNode and
readValue() for POJO?

No, you can use readValue() for JSONNode as well:

ie: JsonNode jn = new ObjectMapper().readValue(src, JsonNode.class);

Additional properties

objectMapper.configure(
    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);

Java 8 lambdas usage:

https://stackoverflow.com/questions/38662582/update-json-values-with-lambda

JsonNode json = new ObjectMapper().readTree(new ObjectMapper().writeValueAsString(myObject));

ObjectNode rootNode = (ObjectNode) json;
ObjectNode resourceNode = (ObjectNode) rootNode.path("resource");
resourceNode.fields().forEachRemaining(
    entry -> resourceNode.set(
        entry.getKey(),
        func(entry.getValue())
    )
);

Java 8 Streams usage:

StreamSupport.stream(jn.spliterator(), false /* or whatever */);