views:

1380

answers:

3

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();
    }
}   
+2  A: 

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:

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

BalusC
Thanks for your answer, I have tried to apply the examples to the following feed: http://www.stocktwits.com/streams/all.json . I didn't manage to get any other values than null. Do I need to create two groups : stream and tweets?
mnml
A: 

I don't know if GSON can do streaming/incremental binding (I thought it did not).

But is there specific reason to only consider that particular library? Other Java JSON processing libraries do allow such processing (you can check links the other answer has for some ideas), since it is quite important feature when processing large feeds.

StaxMan
Well I was using ROME for RSS feeds, and the framework I'm using contains gson, Thats why I'm trying to use it, but I'm open to any other library.
mnml
Ok. Like I said, I think GSON only does full document binding, but I am not 100%.For an alternative, Jackson (http://jackson.codehaus.org) does allow incremental binding, as well as multiple other operating modes.The way that works is that you need to get a JsonParser for the main thing, iterate over main JSON array or object, and call parser.readValueAs() for actual binding.User mailing list can help with details, if documentation does not have enough pointers.
StaxMan
A: 

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

inder