Search code examples
javajsonjacksonjackson-databind

Read the outer-most JSON object but not the inner ones using Jackson?


This is similar to this question but it's a little different.

Let's say I have a json document defined like this:

[
    { "type" : "Type1", 
      "key1" : "value1" },
    { "type" : "Type2", 
      "key2" : "value2" }
]

I want to read this json document into a list of strings (List<String>). I only want to read the outer-most list into the Java List, the json objects inside the list should be left as-is inside the list. The result should be equivalent to this (I ignore newlines etc):

var myList = List.of("{\"type\": \"Type1\", \"key1\": \"value1\"}, {\"type\": \"Type2\", \"key2\": \"value2\"}")

Note that I don't want to create any DTO to hold some intermediate representation. I just want everything below the "list" to be represented "as-is".

How can I achieve this?

I'm using Jackson 2.12.1.


Solution

  • If you don't want to hold intermediate representation in a DTO, then one way in which the required deserialization can be achieved is:

    // Create a ObjectMapper (of type com.fasterxml.jackson.databind.ObjectMapper)
    ObjectMapper mapper = new ObjectMapper();
    // Read the json string into a List. This will be deserialized as a collection of LinkedhashMap
     List<LinkedHashMap> list = mapper.readValue(getInputString(), List.class);
    //Iterate over the deserialized collection and create a JSONObject from every LinkedHashMap
     List<String> result = list.stream()
                               .map(map -> new JSONObject(map).toString())
                               .collect(Collectors.toList());
    

    This will produce:

    [{"key1":"value1","type":"Type1"}, {"key2":"value2","type":"Type2"}]
    

    Downside of this approach is, it takes a hit on performance.