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();
}
}
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.
Gson 1.4 has a new API JsonStreamParser that lets you parse multiple JSON objects one by one from a stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With