4

Say I have a JSON string like:

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

My accessor:

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:

            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 would be the best way to get those sub-arrays for the image here?

1 Answer 1

3

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 that, then your For loop you created will do it, (if not a little clunky, would be better if your JSON is formed 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 the incoming String

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

Job done.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem.. added a bit more to it to explain how your json should be formatted but should work as you had it. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.