Java – Parse JSON arrays with subarrays using GSON?

Parse JSON arrays with subarrays using GSON?… here is a solution to the problem.

Parse JSON arrays with subarrays using GSON?

Let’s say I have a JSON string like this:

{"title":"aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"200 "}, ...

My visitors:

import com.google.gson.annotations.SerializedName;

public class accessorClass {

@SerializedName("title")
    private String title;

@SerializedName("url")
    private String url;

@SerializedName("image")
    private String image;

 how do I place the sub-arrays for the image here?
    ...

public final String get_title() {
        return this.title;
    }

public final String get_url() {
        return this.url;
    }

public final String get_image() {
        return this.image;
    }

...

}

And my main content:

            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonArray Jarray = parser.parse(jstring).getAsJsonArray();

ArrayList<accessorClass > aens = new ArrayList<accessorClass >();

for(JsonElement obj : Jarray )
            {
                accessorClass ens = gson.fromJson( obj , accessorClass .class);
                aens.add(ens);
            }

What do you think is the best way to get a subarray of images here?

Solution

FYI, if your JSON is an array: {“results:”:[{“title”:”aaa","url":"bbb","image":{"url":"ccc","width":"100","height":"20...},{}]}

Then you need a wrapper class:

class WebServiceResult {
    public List<AccessorClass> results;
}

If your JSON

isn’t formatted like this, the For loop you created will do this (if not a bit clunky, it would be better if your JSON was formatted like above).

Create an image class

class ImageClass {
    private String url;
    private int width;
    private int height;

 Getters and setters
}

Then change your AccessorClass

    @SerializedName("image")
    private ImageClass image;

 Getter and setter

Then GSON passes in the String

Gson gson = new Gson();
AccessorClass object = gson.fromJson(result, AccessorClass.class);

The job is done.

Related Problems and Solutions