将复杂的 json 文件反序列化为 POJO - 要么作为一个列表元素工作,要么不作为

Deserializing complex json file into a POJO - works either as one list element, or doesn't

我正在尝试将此 json 反序列化为 POJO class,这样我就可以管理这些对象了。 JSON:

{
 "something": "x",
 "items": [
  {
   "type": "y",
   "id": "123",
   "otherInfo": {
    "tag": "abc",
    "otherId": [
     {
      "first": "qaz",
      "second": "zaq"
     },
     {
[...]

像这样的元素有 10 多个。 我想反序列化它,所以我使用了 jsonschema2pojo,创建了 classes like Item and otherInfo with getters, setters and constructors.

然后我在我的 DAO 中创建了一个 ObjectMapper class:

ObjectMapper mapper = new ObjectMapper();
    Item items;
    {
        try {
            items = mapper.readValue(new File("path/file.json"), Item.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Item getAllItems(){
       return items;
    }

这样我得到一个空输出。 在将 Item 更改为 Item[] 时,我得到 "MismatchedInputException",因为 "something" 在我的 JSON.

中的 "items" 之上

当我尝试引用比项目高一级的 POJO class 时,我将整个 JSON 作为单个数组元素,其中包含所有内容。很明显,但这表明 ObjectMapper 工作正常。

有没有简单或有效的方法来反序列化 JSON 那样的方法?

您可以创建一个包含 ArrayList 的父对象来表示 Item 数组。

例如:

public class MyParentObject {
    String something;
    ArrayList<Item> items;
    public ArrayList<Item> getItems() {
       return items;
    }
    // the rest of your getters/setters
}

// the object mapper line becomes:
MyParentObject parentObject = mapper.readValue(new File("path/file.json"), MyParentObject.class);

ArrayList<Item> items = parentObject.getItems();

通过JSON反序列化,JSON数组可以直接映射到ArrayList。