Rorellanam Rorellanam - 1 year ago 60
Java Question

How to address a Json array response with many objects and properties?

I need help to know what is the recommended way to address a JSON response with a lot of json objects and properties that will be displayed (some of them, the others may be shown in a detail window when user tap on listitem) in a ListView in Android.

So far, I know you might use JSONObject class to get the properties:

JSONObject resultObject = resultsArray.getJSONObject(i);

String title = resultObject.getString("original_title");
String posterPath = resultObject.getString("poster_path");
String overview = resultObject.getString("overview");
String date = resultObject.getString("release_date");

// Create a new {@link Movie} object with the magnitude, location, time,
// and url from the JSON response.
Movie movie = new Movie(title, posterPath, overview, date);

// Add the new {@link Movie} to the list of movies.

But my main doubt is what would happen if the JSON properties are more, i.e 20 properties that need to be added to the ListView:

What would be the best option?, considering that the JSON will contain objects, such as: movies, actors, stats, etc.

May I have to create different Java beans classes in order to create instances?like:

Movie movie = new Movie(title, posterPath, overview, date);

so I want to avoid to have a huge constructor parameter. Should I create only one class and use builder pattern?

Answer Source

You can use GSON library to deserialize your JSON data.

Your Movie class would be like :

class Movie {
    String title;
    String posterPath;
    String overview;
    String date;

And parse it with :

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Movie movie = gson.fromJson(jsonInput, Movie.class);

Then you just need to update your Movie class if you want to add/update fields

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download