简体   繁体   English

使用 ObjectMapper 读取嵌套的 json 文件

[英]Reading nested json file with ObjectMapper

I am trying to read a json file (schools.json) with the help of ObjectMapper.我正在尝试在 ObjectMapper 的帮助下读取 json 文件 (schools.json)。 File structure of json was something like this: json 的文件结构是这样的:

[
  {
    "schoolid": "X",
    "schoolname": "ABC",
    "schoolbranch": "DEF",
  },
 {
    "schoolid": "Y",
    "schoolname": "GDF",
    "schoolbranch": "HJG",
  },
]

And this json file was read from java like below:这个json文件是从java中读取的,如下所示:

static final String fileName = "schools.json";

     InputStream iStream = getClass().getClassLoader().getResourceAsStream(fileName);
          schools = objectMapper.readValue(iStream,
                  objectMapper.getTypeFactory().constructCollectionType(List.class, School.class));

Now I updated the json like this:现在我像这样更新了json:

 [
      {
        "schoolid": "X",
        "schoolname": [{"original": "dfs"},{"translated":  "sfds"}],
        "schoolbranch":  [{"sub": "fdsf5"},{"major": "908fds"}],
      },
     {
        "schoolid": "Y",
        "schoolname": [{"original": "wera"},{"translated":  "sfds"}],
        "schoolbranch":  [{"sub": "mohk"},{"major": "908fds"}],
      },
 ]

Thus School.java is also changed.因此 School.java 也发生了变化。 In previous version every field was a String field.在以前的版本中,每个字段都是一个字符串字段。 Now schoolname and schoolbranch are other models/objects having fields original,translated etc.现在schoolnameschoolbranch是其他具有原始、翻译等字段的模型/对象。

public class School {
private int schoolid;
private SchoolName schoolname;
private SchoolBranch schoolbranch;
... 
// getters and setters here
}

And for example SchoolName.java:例如 SchoolName.java:

public class SchoolName {
private String original;
private String translated;
// etc.
}

Now, the above java code block is not working.现在,上面的 java 代码块不起作用。 schools object returns null.学校对象返回 null。

I could not make this work.我无法完成这项工作。 I found some examples where json field is containing array but I could not apply a similar logic for my case.我发现了一些 json 字段包含数组的示例,但我无法为我的案例应用类似的逻辑。 Help is appreciated.帮助表示赞赏。

As Smutje and Smile said, your json objects are lists not single objects.正如 Smutje 和 Smile 所说,您的 json 对象是列表而不是单个对象。 Change your java School object to:将您的 java School 对象更改为:

public class School {
private int schoolid;
private List<SchoolName> schoolname;
private List<SchoolBranch> schoolbranch;
... 
// getters and setters here
}

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

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