繁体   English   中英

使用 Jackson 解析深度嵌套的 JSON 属性

[英]Parsing deeply nested JSON properties with Jackson

我试图找到一种从API的有效负载解析嵌套属性的干净方法。

以下是JSON有效负载的粗略概括:

{
  "root": {
    "data": {
      "value": [
        {
          "user": {
            "id": "1",
            "name": {
              "first": "x",
              "last": "y"
            }
          }
        }
      ]
    }
  }
}

我的目标是拥有一个包含firstNamelastName字段的User对象数组。

有谁知道一个干净地解析这个的好方法?

现在我正在尝试创建一个Wrapper类,其中包含用于数据、值、用户等的静态内部类,但这似乎是一种混乱的方法,只是为了读取第一个/最后一个属性的数组。

我正在使用restTemplate.exchange()来调用端点。

您需要使用JsonPath库,它允许您仅选择必填字段,然后您可以使用Jackson将原始数据转换为POJO类。 示例解决方案,可能如下所示:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
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("$..value[*].user.name");

        ObjectMapper mapper = new ObjectMapper();
        CollectionType usersType = mapper.getTypeFactory().constructCollectionType(List.class, User.class);
        List<User> users = mapper.convertValue(nodes, usersType);
        System.out.println(users);
    }
}

class User {

    @JsonProperty("first")
    private String firstName;

    @JsonProperty("last")
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "User{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

上面的代码打印:

[User{firstName='x', lastName='y'}]

其他一种使用 lib org.json.simple 的简单方法

JSONParser jsonParser = new JSONParser();
        //Read JSON file
        Object obj = jsonParser.parse(reader);

        JSONObject jObj = (JSONObject) obj;

        JSONObject root = (JSONObject)jObj.get("root");
        JSONObject data = (JSONObject) root.get("data");
        JSONArray value =  (JSONArray) data.get("value");
        JSONObject array = (JSONObject) value.get(0);
        JSONObject user = (JSONObject) array.get("user");
        JSONObject name = (JSONObject) user.get("name");

        String lastName = (String) name.get("last");
        String firstName = (String) name.get("first");

        System.out.println(lastName + " " + firstName);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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