I am trying to read a json file (schools.json) with the help of ObjectMapper. File structure of json was something like this:
[
{
"schoolid": "X",
"schoolname": "ABC",
"schoolbranch": "DEF",
},
{
"schoolid": "Y",
"schoolname": "GDF",
"schoolbranch": "HJG",
},
]
And this json file was read from java like below:
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:
[
{
"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. In previous version every field was a String field. Now schoolname and schoolbranch are other models/objects having fields original,translated etc.
public class School {
private int schoolid;
private SchoolName schoolname;
private SchoolBranch schoolbranch;
...
// getters and setters here
}
And for example SchoolName.java:
public class SchoolName {
private String original;
private String translated;
// etc.
}
Now, the above java code block is not working. schools object returns 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. Help is appreciated.
schoolnameandschoolbranchshould be arrays and not objects.schoolnameandschoolbranchto List/Array in java model, or change your json to"schoolname": {"original": "dfs","translated": "sfds"},