簡體   English   中英

Jackson: Deserialize JSON array from JSON object into Java List

[英]Jackson: Deserialize JSON array from JSON object into Java List

我已經被這個絆倒了一段時間。 我有一個 Spring 應用程序並想解析以下 JSON:

{
  "metadata": {...}
  "response": {
    "objects": [
      {
        "name": "someName",
        "properties": [<array_of_properties>]
      },
      ...
    ]
  }
}

進入以下 Java 對象的列表:

public class MyClass {
  String name;
  List<CustomProperties> customProperties;
}

意思是,我只想提取objects數組並僅解析它。 我曾嘗試使用自定義反序列化器並且有效,但我必須這樣做:

@JsonDeserialize(using=MyDeserializer.class)
public class MyClassList extends ArrayList<MyClass>{}

接着:

ObjectMapper objectMapper = new ObjectMapper();
List<MyClass> list = objectMapper.readValue(json, MyClassList.class) 

無論如何要避免擴展ArrayList ,因為目前我這樣做是為了能夠訪問.class屬性。

你可以用幾個類定義你的 json 結構

public class MyJson {
  private MyResponse response;
  ...
}

public class MyResponse {
  private List<MyClass> objects;
  ...
}

public class MyClass {
  String name;
  List<CustomProperty> customProperties;
  ...
}

您可以使用 Jackson 將 json 字符串解析為MyJson class,不需要特殊的@JsonDeserialize

ObjectMapper objectMapper = new ObjectMapper();
MyJson myJson = objectMapper.readValue(json, MyJson.class);
List<MyClass> list =  myJson.getResponse().getObjects();

請記住,此代碼只是草稿,所有類都應該有設置器(和獲取器),並且需要一些 null 檢查

你可以做這樣的事情。 我覺得這會更干凈

@JsonIgnoreProperties(ignoreUnknown = true)
class Wrapper{
  private Response response;
  //setters, getters
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Response{
  private List<MyClass> objects;
  //setters, getters
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyClass {
  String name;
  List<CustomProperties> customProperties;
  //setters, getters
}

ObjectMapper objectMapper = new ObjectMapper();
Wrapper wrapper = objectMapper.readValue(json, Wrapper.class) 

您可以通過遍歷列表來提取對象和 CustomProperties。 您可以通過@JsonIgnoreProperties(ignoreUnknown = true)僅聲明您感興趣的字段並忽略其他字段(例如,我沒有包含元數據)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM