Novazero
Novazero

Reputation: 553

Parsing Json Using the Gson Library

Hello Im having trouble figuring out how to create an object using the Gson Library in Java. I followed some guides online Link To One Here where they said one has to create each part of the Json structure as classes which I did, but I still get a value of null when the object is created.

Nodes nodes = gson.fromJson(obj.get("Nodes"), Nodes.class);

nodes gives me a null value.

If anyone can help point me out what Im missing or if I created my classes wrong that would be of great help.

Here is the JSON structure which I want to parse and create an object from:

{
"nodes":[
{
"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>Test</p>\n ",
"title":"Test",
"link":"<a href=\"/articles/test\">view</a>",
"updated":"2013-11-12 11:52",
"body":"<p>Test</p>",
"type":"Article"
}
},
{
"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>test</p>\n ",
"title":"Test Event",
"link":"<a href=\"/articles/test-event\">view</a>",
"updated":"2013-11-08 17:56",
"body":"<p>test</p>",
"type":"Article"
}
},
{
"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>Atricle with no image</p>\n ",
"title":"No Image",
"link":"<a href=\"/articles/no-image\">view</a>",
"updated":"2013-11-01 16:39",
"body":"<p>Atricle with no image</p>",
"type":"Article"
}
},
{
"node":{
"image_thumb":"/sites/default/files/styles/square_thumbnail/public/field/image/test_cars_1.jpg",
"image_medium":"/sites/default/files/styles/media_gallery_thumbnail/public/field/image/test_cars_1.jpg",
"body_image":" <p style=\"text-align: justify; font-size: 11px; line-height: 14px; margin-bottom: 14px; font-family: Arial, Helvetica, sans;\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur dapibus massa vitae mauris elementum dignissim. Etiam ut cursus nulla, at accumsan lacus. Vivamus semper massa ut lorem pulvinar, et porta magna commodo. Quisque tempus ligula eget nisi condimentum lobortis. Praesent in tincidunt massa. Fusce eleifend interdum justo a malesuada. Pellentesque eget condimentum mi, sed congue enim.</p>\n<p style=\"text-align: justify; font-size: 11px; line-height: 14px; margin-bottom: 14px; font-family: Arial, Helvetica, sans;\">Nam ornare pretium volutpat. Sed vitae dolor odio. Cras eleifend tellus at ultrices vehicula. Aenean luctus auctor hendrerit. Nullam egestas at lectus sed scelerisque. Aenean nec sagittis tellus. Aenean nec nibh non erat pellentesque hendrerit id sed quam. Phasellus id dapibus metus. Nunc ultricies enim vitae aliquet semper. Fusce eu mollis elit.</p>\n ",
"title":"Testing it Up",
"subtitle":"As we do",
"link":"<a href=\"/articles/testing-it\">view</a>",
"updated":"2013-10-31 13:31",
"body":"<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur dapibus massa vitae mauris elementum dignissim. Etiam ut cursus nulla, at accumsan lacus. Vivamus semper massa ut lorem pulvinar, et porta magna commodo. Quisque tempus ligula eget nisi condimentum lobortis. Praesent in tincidunt massa. Fusce eleifend interdum justo a malesuada. Pellentesque eget condimentum mi, sed congue enim.</p><p>Nam ornare pretium volutpat. Sed vitae dolor odio. Cras eleifend tellus at ultrices vehicula. Aenean luctus auctor hendrerit. Nullam egestas at lectus sed scelerisque. Aenean nec sagittis tellus. Aenean nec nibh non erat pellentesque hendrerit id sed quam. Phasellus id dapibus metus. Nunc ultricies enim vitae aliquet semper. Fusce eu mollis elit.</p>",
"type":"Article"
}
}
]
}

Here is a class I created which makes an http request to return Json data, and also try using the Gson library here to create an object based on the returned Json structure.

private class NewsAsyncTask extends AsyncTask<Void, Void, Void> {

@Override
protected Void doInBackground(Void... params) {
    String url = "http://imsa.com/series/united-sportscar/news.json/";
    HttpGet getRequest = new HttpGet(url);

    try{
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse getResponse = httpClient.execute(getRequest);
        final int statusCode = getResponse.getStatusLine().getStatusCode();

        if(statusCode != HttpStatus.SC_OK) {
            Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
        }

        HttpEntity getResponseEntity = getResponse.getEntity();
        InputStream httpResponseStream = getResponseEntity.getContent();
        InputStreamReader inputStreamReader = new InputStreamReader(httpResponseStream);

        JsonParser parser = new JsonParser();
        JsonObject obj = parser.parse(inputStreamReader).getAsJsonObject();


        Gson gson = new Gson();
        Nodes nodes = gson.fromJson(obj.get("Nodes"), Nodes.class);
        System.out.println(nodes.getNews());
    }
    catch (IOException e) {
        getRequest.abort();
        Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }

    return null;
}

The following are all the classes I used that make up the Json structure I want to parse:

Nodes Class -

public class Nodes implements Serializable {

    @SerializedName("nodes")
    private final ArrayList<News> news;

    public Nodes(final ArrayList<News> news) {
        this.news = news;
    }

    public Nodes(final Nodes nodesToCopy) {
        this.news = nodesToCopy.getNews();
    }

    public ArrayList<News> getNews() {
        return news;
    }

    @Override
    public String toString() {
        return "Nodes{" +
                "news=" + news +
                '}';
    }
}

News class -

public class News {

    @SerializedName("node")
    ArrayList<NewsItem> news;

    public News(ArrayList<NewsItem> news) {
        this.news = news;
    }

    public ArrayList<NewsItem> getNews() {
        return news;
    }

    @Override
    public String toString() {
        return "News{" +
                "news=" + news +
                '}';
    }
}

NewsItem Class -

public class NewsItem implements Serializable {

    @SerializedName("image_thumb")
    private final String imageThumb;

    @SerializedName("image_medium")
    private final String imageMedium;

    @SerializedName("body_image")
    private final String bodyImage;

    @SerializedName("title")
    private final String title;

    @SerializedName("link")
    private final String link;

    @SerializedName("updated")
    private final Date updated;

    @SerializedName("body")
    private final Text body;

    @SerializedName("type")
    private final String type;

    public NewsItem(String imageThumb, String imageMedium, String bodyImage, String title, String link, Date updated, Text body, String type) {
        this.imageThumb = imageThumb;
        this.imageMedium = imageMedium;
        this.bodyImage = bodyImage;
        this.title = title;
        this.link = link;
        this.updated = updated;
        this.body = body;
        this.type = type;
    }

    public NewsItem(final NewsItem newsItemToCopy) {
        this.imageThumb = newsItemToCopy.getImageThumb();
        this.imageMedium = newsItemToCopy.getImageMedium();
        this.bodyImage = newsItemToCopy.getBodyImage();
        this.title = newsItemToCopy.getTitle();
        this.link = newsItemToCopy.getLink();
        this.updated = newsItemToCopy.getUpdated();
        this.body = newsItemToCopy.getBody();
        this.type = newsItemToCopy.getType();
    }

    public String getImageThumb() {

        return imageThumb;
    }

    public String getImageMedium() { return imageMedium; }

    public String getBodyImage() {
        return bodyImage;
    }

    public String getTitle() {
        return title;
    }

    public String getLink() {
        return link;
    }

    public Date getUpdated() {
        return updated;
    }

    public Text getBody() {
        return body;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "NewsItem{" +
                "imageThumb='" + imageThumb + '\'' +
                ", imageMedium='" + imageMedium + '\'' +
                ", bodyImage='" + bodyImage + '\'' +
                ", title='" + title + '\'' +
                ", link='" + link + '\'' +
                ", updated=" + updated +
                ", body=" + body +
                ", type='" + type + '\'' +
                '}';
    }
}

Upvotes: 2

Views: 2479

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280172

There are a lot of things wrong here, but they are relatively easy to fix.

First

JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(inputStreamReader).getAsJsonObject();

obj now contains your full JSON. So when you do

obj.get("Nodes")

you are getting the array object called nodes inside this whole JSON. But your Nodes class requires it. So Gson won't find anything and will return null. You need to give obj directly to the fromJson call.

Second, each node element is a JSON object

"node":{
"image_thumb":"/sites/all/themes/imsa/images/headlines-thumb.png",
"body_image":" <p>Test</p>\n ",
"title":"Test",
"link":"<a href=\"/articles/test\">view</a>",
"updated":"2013-11-12 11:52",
"body":"<p>Test</p>",
"type":"Article"
}

not a JSON array. Therefore this

@SerializedName("node")
ArrayList<NewsItem> news;

is wrong. An ArrayList assumes an array structure, not a single element. Change that (and the mutators/accessors) to

@SerializedName("node")
NewsItem news;

Finally, you haven't set a Date format so Gson won't know how to deserialize

"2013-11-12 11:52"

into a Date object. You can set your own Date format and get a properly configured Gson object like so

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();

Upvotes: 3

Related Questions