0

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.

2
  • 2
    schoolname and schoolbranch should be arrays and not objects. Commented Mar 25, 2020 at 8:47
  • 2
    Either change schoolname and schoolbranch to List/Array in java model, or change your json to "schoolname": {"original": "dfs","translated": "sfds"}, Commented Mar 25, 2020 at 8:49

1 Answer 1

1

As Smutje and Smile said, your json objects are lists not single objects. Change your java School object to:

public class School {
private int schoolid;
private List<SchoolName> schoolname;
private List<SchoolBranch> schoolbranch;
... 
// getters and setters here
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.