Parsing a subset of JSON in Java using Jackson

前端 未结 3 1023
谎友^
谎友^ 2021-02-14 22:15

Given a Json, is it possible to use Jackson to only parse out a section of the message? Say that the data I\'m interested in is buried in a deep hierarchy of fields and I simply

相关标签:
3条回答
  • 2021-02-14 22:38
    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readTree("... your JSON ...");
    

    Using the JsonNode object you can then call get("my").get("deep").get("structure") to get the node you want.

    Once you got your hands on that node, a simple call to mapper.treeToValue(myDeepJsonNode, Telephone[].class) will get you your array ofTelephone. You can get a list using a TypeReference as well.

    To get to your deep JsonNode you can also use the findValue and findPath methods.

    The Javadoc: https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html

    0 讨论(0)
  • 2021-02-14 22:50

    Yes, it is possible the way you have mentioned in the Pseudo code. "phoneNumbers" is a key and value returned can be passed on to Jackson deserialiying.

    If the response is an array of maps then you can iterate through each one of them and use the yourResponseAsJSONObject.get('phoneNumbers') method to get the value and pass it on to Jackson

    or use JsonPath as mentioned by @dimas

    0 讨论(0)
  • 2021-02-14 22:51

    You can use JsonPath library. With this library you can map your JsonPath output directly into POJO's.

    Pseudo:

    List<Telephone> phoneNrs = JsonPath.parse(json).read("$.my.deep.structure.persons.phoneNumbers", List.class);
    
    0 讨论(0)
提交回复
热议问题