Skip to content Skip to sidebar Skip to footer

Retrieve Data Using Gson

I have pasted my code below and would appreciate it if someone would help me work through it. When I run my activity a list should be getting updated inside of my app. I haven't be

Solution 1:

It looks to me like you are trying to use Gson in a way too complicated way.

(Also, what are JSONParse and JSONObject in your code? From org.json or Jackson apparently. Why on earth would you use several different JSON libraries in the same piece of code? Just stick to Gson!)

If we begin with your original JSON string:

{"begin":[{"id":1,"name":"1","size":2},{"id":2,"name":"2","size":2}],"end":[{"id":1,"name":"1","size":2},{"id":2,"name":"2","size":2}]}

A natural way to model that into Java objects would be something like this, using two classes:

publicclassTopLevel{
    List<Main> begin;
    List<Main> end;
}

publicclassMain{
    String id;
    String name;
}

(Feel free to rename "TopLevel" to something better, to whatever it represents in your application.)

Now, parsing the JSON into Java objects (one TopLevel object containing a total of 4 Main objects), is as simple as:

Gsongson=newGsonBuilder().create();
TopLeveltopLevel= gson.fromJson(jsonString, TopLevel.class);

Post a Comment for "Retrieve Data Using Gson"