Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Json Feeds with google Gson

I would like to know how to parse a JSON feed by items (eg. url / title / description for each item). I have had a look to the doc / api but, it didn't help me.

This is what I got so far

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class ImportSources extends Job {
    public void doJob() throws IOException {
        String json = stringOfUrl("http://feed.test/all.json");
        JsonObject jobj = new Gson().fromJson(json, JsonObject.class);
        Logger.info(jobj.get("responseData").toString());
    }
    public static String stringOfUrl(String addr) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        URL url = new URL(addr);
        IOUtils.copy(url.openStream(), output);
        return output.toString();
    }
}   
like image 428
Roch Avatar asked Jan 09 '10 19:01

Roch


2 Answers

Depends on the actual JSON format. You can in fact just create a custom Javabean class which matches the JSON format. Any fields in JSON can be mapped as String, Integer, Boolean, etc Javabean properties. Any arrays can be mapped as List properties. Any objects can be mapped as another nested Javabean property. It greatly eases further processing in Java.

Without a JSON string example from your side, it's only guessing how it would look like, so I can't give a basic example here. But I've posted similar answers before here, you may find it useful:

  • Converting JSON to Java
  • Generate Java class from JSON?

Gson has also an User Guide, you may find it useful as well.

like image 70
BalusC Avatar answered Sep 21 '22 02:09

BalusC


Gson 1.4 has a new API JsonStreamParser that lets you parse multiple JSON objects one by one from a stream.

like image 44
inder Avatar answered Sep 24 '22 02:09

inder