简体   繁体   English

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

[英]Parsing deeply nested JSON properties with Jackson

I am trying to find a clean way of parsing nested properties from a payload from an API .我试图找到一种从API的有效负载解析嵌套属性的干净方法。

Here is a rough generalisation of the JSON payload:以下是JSON有效负载的粗略概括:

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

My goal is to have an array of User objects which have firstName and lastName fields.我的目标是拥有一个包含firstNamelastName字段的User对象数组。

Does anyone know a good way to parse this cleanly?有谁知道一个干净地解析这个的好方法?

Right now I am trying to create a Wrapper class and within that have static inner classes for data, value, user etc. but this seems like a messy way of doing this just to read the array of first/last properties.现在我正在尝试创建一个Wrapper类,其中包含用于数据、值、用户等的静态内部类,但这似乎是一种混乱的方法,只是为了读取第一个/最后一个属性的数组。

I am using restTemplate.exchange() to call the endpoint.我正在使用restTemplate.exchange()来调用端点。

You need to use JsonPath library which allow you to select only required fields and after that you can use Jackson to convert raw data to POJO class.您需要使用JsonPath库,它允许您仅选择必填字段,然后您可以使用Jackson将原始数据转换为POJO类。 Example solution, could look like below:示例解决方案,可能如下所示:

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 + '\'' +
                '}';
    }
}

Above code prints:上面的代码打印:

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

else one simple way with lib org.json.simple其他一种使用 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