使用Jackson在Java中解析JSON的子集 [英] Parsing a subset of JSON in Java using Jackson

查看:117
本文介绍了使用Jackson在Java中解析JSON的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于Json,是否可以使用Jackson仅解析消息的一部分?
假设我感兴趣的数据埋藏在深层次的字段中,我根本不关心为每个类创建DTO类。

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 do not care about creating DTO classes for each and every class.

鉴于一个非常简化的场景我想建模电话类而不知道它之前的结构:

Given a very simplified scenario I'd like to model the Telephone class without knowing anything about the structure before it:

...{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}....

我正在考虑使用json-path和反序列化我感兴趣的部分。一些伪:

I'm thinking something in the terms of using json-path together with deserializing just the parts I'm interested of. Some pseudo:

List<Telephone> phoneNrs = parse(".my.deep.structure.persons.phoneNumbers", List<Telephone.class>);


推荐答案

ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree("... your JSON ...");

使用 JsonNode 对象,然后可以调用 get(my)。get(deep)。get(structure)获取所需的节点。

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

一旦你掌握了那个节点,只需简单调用 mapper.treeToValue(myDeepJsonNode,Telephone [] .class)就可以得到你的数组电话。您也可以使用 TypeReference 获取列表。

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.

要深入 JsonNode 你也可以使用 findValue findPath 方法。

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

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

这篇关于使用Jackson在Java中解析JSON的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆