-1

I'm using TheMovieDB API in my assignment work for University and I'm having difficulty understanding how to access values from its nested JSON file format.

The following is a link to the file I am trying to use: https://api.themoviedb.org/3/discover/movie?api_key=822b6a3af922b0c70d5455e2d2e0f782&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=true&page=1

Currently, my code looks like this:

 httpConnect jParser = new httpConnect();
 String json = jParser.getJSONFromUrl(url);
 jsonData = json.toString();

 JSONObject json1obj = new JSONObject(json);
 JSONArray json1arr = json1obj.getJSONArray("results");
 String jsonResults = json1arr.toString();

 JSONObject first = new JSONArray(jsonResults).getJSONObject(0);
 JSONArray second = first.getJSONArray("poster_path");
 String secondString = second.toString();

 poster_path = secondString.toString();

I am able to access the first layer ("results") but I'm having trouble going any deeper than that. The overall goal is to access the "poster_path" object. I'm new to Java and JSON so this may seem like a silly question. Any help is appreciated :)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Jack
  • 73
  • 2
  • 9

3 Answers3

0

From my experience, dont try to invent wheel twice, create a model class with the atributtes of the object youre retrieving from server, then import gson library(google json parsing library), add this to your build gradle file --> compile 'com.google.code.gson:gson:2.7'

public class YourObject(){

    String id;
    String property;

 public YourObject(){}

 //Getter & Setter

}

Gson gson = new Gson();
YourObject item = gson.fromJson(json,YourObject.class);

If what u want to retrieve is a list of some kind of item the approach will be like this

yourObjectListOfItems= new Gson().fromJson(json,newTypeToken<List<YourObject>>(){}.getType());

VERY IMPORTANT - the atributte name must match the json hashmap key for this to work

If the Json structure doesnt match a typical object representation, because it encloses various level of depth the way would be trying to convert the json string into JSONObject or JSONArray depending and putting the new JSON****() inside a try catch block and depending what you expect to be inside you try to convert to JSONArray, JSONObject or decide you havve reached the deepest level so you cannot parse further.

marcos E.
  • 477
  • 4
  • 11
0

You could go with the GSON library (https://github.com/google/gson)

First, add this to your app build.gradle dependencies:

'com.google.code.gson:gson:2.8.0'

Than, go to: http://www.jsonschema2pojo.org and paste your JSON, selecting the right options (JSON instead of JSON Schema, Gson, etc).

You will get all the classes you need to represent your JSON.

For instance, the website will generate many classes, but the first one will be:

public class RootClass {

@SerializedName("page")
@Expose
private Integer page;
@SerializedName("results")
@Expose
private List<Result> results = new ArrayList<Result>();
@SerializedName("total_results")
@Expose
private Integer totalResults;
@SerializedName("total_pages")
@Expose
private Integer totalPages;

/**
* 
* @return
* The page
*/
public Integer getPage() {
return page;
}

/**
* 
* @param page
* The page
*/
public void setPage(Integer page) {
this.page = page;
}

/**
* 
* @return
* The results
*/
public List<Result> getResults() {
return results;
}

/**
* 
* @param results
* The results
*/
public void setResults(List<Result> results) {
this.results = results;
}

/**
* 
* @return
* The totalResults
*/
public Integer getTotalResults() {
return totalResults;
}

/**
* 
* @param totalResults
* The total_results
*/
public void setTotalResults(Integer totalResults) {
this.totalResults = totalResults;
}

/**
* 
* @return
* The totalPages
*/
public Integer getTotalPages() {
return totalPages;
}

/**
* 
* @param totalPages
* The total_pages
*/
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}

}

Than, you can use:

Gson gson = new Gson();
RootClass item = gson.fromJson(json, RootClass.class);

Because your JSON is not a array, is a object.

But probably you need to iterate over the pages because there are 297964 items and 14899 pages!

caiolopes
  • 561
  • 8
  • 14
  • How does this differ from the existing answer? – OneCricketeer Nov 08 '16 at 17:28
  • @cricket_007 it is detailed for the question in case he has difficulties.. Can't I try giving an answer just because is similar to another given answer? Generally answers are similar, don't you think? It is not a competition, I am trying to help because I had the same problem when I was learning... – caiolopes Nov 08 '16 at 17:30
0

GSON is useful and easy, and I would definitely recommend it for any long term/reusable project. However, you can achieve your goal using what you already have without worrying about a POJO. The "result" field is a JSONArray that contains JSONObjects. So, loop through each JSONObject, and pull out the 'poster_path' string from there. And, just to clarify, the "poster_path" field is a string, not an object. If the poster paths are all you need, you can use something like this. The method names may not be exactly the same, but they should be similar. I took the liberty of shortening some of the things you had in there.

httpConnect jParser = new httpConnect();
JSONObject json1obj = new JSONObject(jParser.getJSONFromUrl(url));
JSONArray json1arr = json1obj.getJSONArray("results");
List<String> posterPaths = new ArrayList<String>(json1arr.length());  
for (int i = 0 ; i < json1arr.length(); i++) {
    JSONObject ithObject = json1arr.getJSONObject(i);
    // if necessary, check to make sure the key 'poster_path' exists
    if (ithObject.has("poster_path")) {
        posterPaths.add(ithObject.getString("poster_path"));
    }
}

// as an example usage, loop through the list and print each poster path
for (String posterPath : posterPaths) {
    System.out.println(posterPath);
}

I see the value in writing POJOs and creating a more robust solution, but this may be a good place to start since you are new to Java/JSON.

gregbert
  • 446
  • 2
  • 5
  • Thank you for this! Everyone's answers were great but this is exactly what I wanted and with a minimal amount of code :) – Jack Nov 11 '16 at 21:13