Parsing a subset of JSON in Java using Jackson

前端 未结 4 2316
花落未央
花落未央 2021-02-14 21:51

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

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 22:43

    To do this efficiently with Jackson, use the Streaming API via the JsonParser class (http://fasterxml.github.io/jackson-core/javadoc/2.5/com/fasterxml/jackson/core/JsonParser.html).

    This approach will allocate no additional memory and will not incur the cost of deserializing values for all of the skipped data. Since the code will be much longer and more difficult to read than using Jackson's ObjectMapper, only do this if profiling shows unacceptable GC activity or CPU usage during parsing.

    You can skip all of the nodes that you are uninterested in until you hit the "phoneNumbers" key. Then you can call the readValueAs function to deserialize the array of phone number dictionaries like so readValueAs(new TypeReference()).

    See also:

    • a tutorial on reading and writing with JsonParser: http://www.cowtowncoder.com/blog/archives/2009/01/entry_132.html
    • The main documentation: https://github.com/FasterXML/jackson-core

提交回复
热议问题