簡體   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