Parsing a JSON array with a submatrix with GSON?

Say I have a JSON string, for example:

{"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 is the best way to get these subarrays for an image here?

+4
source share
1 answer

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 is not formatted this way, then your For loop that you created will do it (if not a little clumsy, it would be better if your JSON is generated as above).

Create 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 input line

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

The task is completed.

+3
source

Source: https://habr.com/ru/post/1401198/


All Articles