javajsonparsingjacksonfasterxml

Jackson JsonParser get Array token


I am using Jackson Json Parser to get values out of a JSON string and then plugging them into a Java Object. Here is a chunk of the sort of JSON I am dealing with:

{
    "address":"aURL",
    "links":[
        "aURL",
        "aURL",
        "aURL"
    ]
}

Here is what I have going on in my Java code. net is a global ArrayList, Page objects have a String address field and a String[] links field. I want to get the String array of links out of the JSON and plug them into a Page object. While I can easily extract the address string with the getText() method, I cannot figure a convenient way to just grab the String array. Here's my code right now:

private static void parse(String json) throws IOException {
    JsonParser parser = new JsonFactory().createJsonParser(json);
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        String tok = parser.getCurrentName();
        Page p = new Page();
        if ("address".equals(tok)) {
            parser.nextToken();
            p.setAddress(parser.getText());
        }
        if ("links".equals(tok)) {
            parser.nextToken();
            //p.setLinks(HOW TO GET STRING ARRAY)
        }
        net.add(p);
    }
}

I would prefer to stick with the JsonParser nexting method I am using, unless it's just gonna be too unwieldy.


Solution

  • You can try something like this.

    private static void parse(String json) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonParser parser = new JsonFactory().createJsonParser(json);
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String tok = parser.getCurrentName();
            Page p = new Page();
            if ("address".equals(tok)) {
                parser.nextToken();
                p.setAddress(parser.getText());
            }
            if ("links".equals(tok)) {
                parser.nextToken();
                ArrayNode node = objectMapper.readTree(parser);
                Iterator<JsonNode> iterator = node.elements();
                String[] array = new String[node.size()];
                for (int i = 0; i < node.size(); i++) {
                    if (iterator.hasNext()) {
                        array[i] = iterator.next().asText();
                    }
                }
                p.setLinks(array);
            }
            net.add(p);
        }
    }