我正在尝试在ObjectMapper的帮助下读取json文件(schools.json)。json的文件结构如下:
[
{
"schoolid": "X",
"schoolname": "ABC",
"schoolbranch": "DEF",
},
{
"schoolid": "Y",
"schoolname": "GDF",
"schoolbranch": "HJG",
},
]
而且这个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));
现在我像这样更新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"}],
},
]
因此School.java也已更改。在以前的版本中,每个字段都是一个String字段。现在schoolname和schoolbranch是其他具有原始字段,翻译字段等的模型/对象。
public class School {
private int schoolid;
private SchoolName schoolname;
private SchoolBranch schoolbranch;
...
// getters and setters here
}
例如,SchoolName.java:
public class SchoolName {
private String original;
private String translated;
// etc.
}
现在,以上的Java代码块不起作用。 schools对象返回null。
我无法完成这项工作。我发现了一些示例,其中json字段包含数组,但是无法为我的案例应用类似的逻辑。感谢帮助。
正如Smutje和Smile所说,您的json对象是列表,而不是单个对象。将您的java School对象更改为:
public class School {
private int schoolid;
private List<SchoolName> schoolname;
private List<SchoolBranch> schoolbranch;
...
// getters and setters here
}