简体   繁体   中英

Extracting objects from an array with Jackson Streaming API

I've been trying to use the Jackson Streaming API in Java to process the following:

{
  "objs": [
    {
      "A": {
        "a": "b",
        "c": "d"
      },
      "B": {
        "e": "f",
        "g": "h"
      },
    },
    {
      "C": {
        "i": "j",
        "k": "l"
      },
      "D": {
        "m": "n",
        "o": "p"
      },
    }
  ]
}

For each top-level object within the array under the objs key (in this example the object with keys "A" and "B", and the other object with keys "C" and "D") I want to extract the objects each as a raw String; I'll potentially have tens of thousands of these to parse so I don't want to map them to model objects.

I'm having trouble figuring out how to do this, because as I iterate over the JSON tokens I cannot identify a boolean condition that tells me I am at the exact beginning of one of these objects. Furthermore, once I have identified that beginning how do I extract the object with the streaming API, and then move on to the next one?

I'm used to using Jackson's automatic deserialization features, and this is throwing me off when trying to think about it in a streaming context.

Your scenario should be easily solved with JsonPath library which solves problems like this. Below example prints all required sub-nodes:

import com.jayway.jsonpath.JsonPath;

import java.io.File;
import java.util.List;
import java.util.Map;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        List<Map> nodes = JsonPath.parse(jsonFile).read("$.objs.*.*");
        nodes.forEach(System.out::println);
    }
}

prints:

{a=b, c=d}
{e=f, g=h}
{i=j, k=l}
{m=n, o=p}

Using Jackson you can do that reading given JSON payload as tree using readTree method. See below example:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.io.File;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(jsonFile);
        ArrayNode objs = (ArrayNode) root.at("/objs");
        objs.forEach(node -> {
            node.forEach(property -> {
                System.out.println(property.toString());
            });
        });
    }
}

Above code prints:

{"a":"b","c":"d"}
{"e":"f","g":"h"}
{"i":"j","k":"l"}
{"m":"n","o":"p"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM