jackson arraynode

12,219

Assuming that a row is one of the entries in a ArrayNode the following simple approach may be useful. It uses the JsonNode abstraction instead of a series of nested Map objects which I personally prefer since JsonNode provides a series of utility methods that are helpful when dealing with this kind of data (data where the structure is possibly unknown or very dynamic so that it can't be easily transformed to a POJO).

The testcase below illustrates how to find the number of rows and how to print the values. To get hold of the values the method JsonNode.elements() is used and the number of rows is simply a call to the size()-method.

public class ArrayNodeTest {
    @Test
    public void verifySizeAndPrintRows() throws IOException {
        final String jsonStr =
                "[{\"key11\":\"value11\",\"key12\":\"value12\"},\n" +
                        "{\"key21\":\"value21\",\"key22\":\"value22\"},\n" +
                        "{\"keyn1\":\"valuen1\",\"keyn2\":\"valuen2\"}]";

        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode jsonNode = mapper.readTree(jsonStr);

        // Verify size
        Assert.assertEquals(3, jsonNode.size());

        // And print rows
        for (final JsonNode row : jsonNode) {
            final Iterable<JsonNode> iterable = () -> row.elements();
            iterable.forEach(elem -> System.out.println(elem.asText()));
        }
    }
}
Share:
12,219
Progress Programmer
Author by

Progress Programmer

evolving...

Updated on June 04, 2022

Comments

  • Progress Programmer
    Progress Programmer almost 2 years

    I have a input json object that contains a array as shown below:

    [{"key11":"value11","key12":"value12"},
    {"key21":"value21","key22":"value22"},
    ...
    {"keyn1":"valuen1","keyn2":"valuen2"}]
    

    I would like to use jackson parser ,firstly, to identify the number of rows and secondly, print only the values on the screen. I want it to be as lightweight as possible. Can anyone point me to a direction?