Dev
Dev

Reputation: 791

Deserialize JSON with Gson in an object

I have a JSON string such as below. That comes from a Website (the URL outputs below to a page) which I'm using in an android application.

{"posts": [{"id":"0000001","longitude":"50.722","latitude":"-1.87817","position":"Someplace 1","altitude":"36","description":"Some place 1 "},{"id":"0000002","longitude":"50.722","latitude":"-1.87817","position":"Some PLace 2","altitude":"36","description":"Some place 2 description"}]}

I would like to deserialize this into a List where I can iterate through them later on the application. How do I do this? I have created a class with properties and methods and a List class as below and then using fromJson to deserialize it, but it returns NULL. Hope the question is clear and many thanks in advance.

ListClass

package dataaccess;

import java.util.List;

public class LocationList {
    public static List<Location> listLocations;

    public void setLocationList(List <Location> listLocations) {
        LocationList.listLocations = listLocations;
    }

    public List<Location> getLocationList() {
        return listLocations;
    }
}

GSON

public LocationList[] getJsonFromGson(String jsonURL) throws IOException{
    URL url = new URL(jsonURL);
    String content = IOUtils.toString(new InputStreamReader(url.openStream()));
    LocationList[] locations =  new Gson().fromJson(content, LocationList[].class);

    return locations;
}

Upvotes: 2

Views: 5174

Answers (2)

Paresh Mayani
Paresh Mayani

Reputation: 128458

What if this JSON response can be parsed using native classes, here is a solution for the same:

String strJsonResponse="Store response here";
JsonObject obj = new JsonObject(strJsonResponse);
JsonArray array = obj.getJsonArray("posts");

for(int i=0; i<array.length; i++)
{
   JsonObject subObj = array.getJsonObject(i);
   String id = subObj.getString("id");
   String longitude = subObj.getString("longitude");
   String latitude = subObj.getString("latitude");
   String position = subObj.getString("position");
   String altitude = subObj.getString("altitude");
   String description = subObj.getString("description");

   // do whatever procedure you want to do here
}

Upvotes: 2

Yogu
Yogu

Reputation: 9455

You try to deserialize into an array of LocationList objects - that surely wasn't your intent, was it? The json snippet doesn't contain a list of lists.

I would drop the class LocationList (except it ought to be extened in future?), and use a pure List. Then, you have to create a type token like this:

java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<ArrayList<Location>>() {}.getType();
List<Location> locations = new Gson().fromJson(content, type);

Upvotes: 2

Related Questions