"movies": [
{
"name": "Good omens",
"year": 2019,
"description": "TV Series",
"director": {
"fullName": "Douglas Mackinnon"
},
"cast": [
{
"fullName": "Michael Sheen",
"role": "Aziraphale"
},
{
"fullName": "David Tennant",
"role": "Crowley"
}
]
]
My reader
public Movie[] getValueOfMovie()throws Exception{
JSONParser parser = new JSONParser();
try(FileReader reader = new FileReader("movies.json")){
JSONObject rootJsonObj = (JSONObject) parser.parse(reader);
JSONArray moviesJsonArray = (JSONArray)rootJsonObj.get("movies");
Movie[] films = new Movie[moviesJsonArray.size()];
Integer q=0;
for (Object mO: moviesJsonArray){
JSONObject moviesJsonObj = (JSONObject) mO;
films[q] = new Movie((String) moviesJsonObj.get("name"),
(Long) moviesJsonObj.get("year"),
(String) moviesJsonObj.get("description"),
(Director) moviesJsonObj.get("director"),
(Cast) moviesJsonObj.get("cast"));
q = q + 1;
}
return films;
}catch(FileNotFoundException e){
e.printStackTrace();
}
return null;
}
My Movie file
public class Movie {
private String name;
private long year;
private String description;
Director director;
Cast cast;
public Movie(String name, long year, String description, Director director, Cast cast) {
this.name = name;
this.year = year;
this.description = description;
this.director = director;
this.cast = cast;
}
I couldn't make a proper pass to the director and cast. I tried to do my reader without them and it worked so problem about how I can get info from the director and cast in my reader. The error was ClassCastexception (class org.json.simple.JSONObject cannot be cast to class Director (org.json.simple.JSONObject and Director are in unnamed module of loader 'app'))
1 Answer 1
json-simple does not know about your classes. Instead, its model consists of the following types
JSONObjectJSONArrayStringBooleanNumber
This means that every time you want a class that is not from this list, you have to construct it yourself. In fact, you already did this with the Movie class.
films[q] = new Movie((String) moviesJsonObj.get("name"), /* other parameters */ );
Equivalently, you can handle a Director class like
JSONObject directorJsonObj = (JSONOBject) moviesJsonObj.get("director");
Director director = new Director((String) directorJsonObj.get("fullName");
Furthermore, you correctly handled an array of Movies.
JSONArray moviesJsonArray = (JSONArray) rootJsonObj.get("movies");
Movie[] films = new Movie[moviesJsonArray.size()];
Integer q = 0;
for (Object mO : moviesJsonArray) {
films[q] = new Movie(/* parameters */);
q = q + 1;
}
This can be transferred to an array of Actors.
JSONArray castJsonArray = (JSONArray) moviesJsonObj.get("cast");
Actor[] cast = new Actor[castJsonArray.size()];
int q = 0;
for (Object obj : moviesJsonArray) {
cast[q] = new Actor(/* parameters */);
q++;
}