Reputation: 43
What did we do? We are working on an Exam with an Movie API and we are getting JSON back. We tried manually to extract the 'inner' JSON part an our Method is working well. We are getting all Data right. We converted it with GSON. But its a nested JSON. We´ve tried several methods from here and other sources as well for nested JSON. We just want to get the "results" part out of it. Whats wrong with our Code? It may be just a little Mistake but we can´t figure it out.
public void test() {
int status = 0;
String inputLine = "";
System.out.println("Test Methode");
try {
String name = " The Italien Job";
URL url = new URL("https://api.themoviedb.org/3/search/movie?"
+ "api_key=/Notforyou:D/language=en-US&"
+ "query=Spirited%20Away&page=1&include_adult=false");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
status = con.getResponseCode();
System.out.println("Status " + status);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
System.out.println("Ausgabe 1 " + inputLine);
if (status == 200) {
System.out.println("Ausgabe 2 " + inputLine);
//Gson gson = new Gson();
//List<Film> filme = gson.fromJson(inputLine.toString(), List.class);
Type listType = new TypeToken<ArrayList<Film>>(){}.getType();
List<Film> yourClassList = new Gson().fromJson(inputLine, listType);
System.out.println("Anzahl Filme " + yourClassList.size());
} else {
System.out.println("Fehler in dem Request");
}
}
in.close();
con.disconnect();
} catch (MalformedURLException ex) {
Logger.getLogger(theMovieDB.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(theMovieDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Edit: the Json. we want the inner part. After the "results". Please ignore the quotation marks. I just typed it in fast.
{
„page“ : 1,
„total_results“:1,
„total_pages“:1,
„results“:[
{
„vote_count“:5511,
„id“:129,
„video“: false,
„vote_average“:8.5,
„title“:"Spirited Away",
„popularity“: 24.739224,
„original_language“:“ja“,
„release_date“: „2001-07-20“
}
]
}
I hope somebody can help. Thanks ^^
Upvotes: 0
Views: 1184
Reputation: 96
You need to first get results JSONArray from JSON response which is having all the films and further need to convert it to a list of films.
It can be achieved using below code:
JsonObject jsonObject = (new JsonParser())
.parse(content.toString().trim()).getAsJsonObject();
JsonArray films = ((JsonArray) jsonObject.get("results"));
Type listType = new TypeToken<ArrayList<Film>>(){}.getType();
List<Film> yourClassList = new Gson().fromJson(films, listType);
Upvotes: 1