Parsing Json Feeds with Google Gson

I would like to know how to parse a JSON feed into elements (e.g. url / title / description for each element). I looked at doc / api, but that 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(); } } 
+7
java json gson parsing
source share
4 answers

Depends on the actual JSON format. In fact, you can simply create a custom Javabean class that conforms to the JSON format. Any fields in JSON can be displayed as String , Integer , Boolean , etc. Javabean Properties. Any arrays can be displayed as List properties. Any objects can be displayed as another Javabean attached property. This greatly facilitates further processing in Java.

Without an example JSON string from the side, it only guesses how it will look, so I cannot give a basic example here. But I already posted similar answers before this, you may find this useful:

  • Convert JSON to Java
  • Create Java class from JSON?

Gson also has a User Guide , you may also find it useful.

+9
source share

Gson 1.4 introduces a new JsonStreamParser API that allows you to parse multiple JSON objects one by one from a stream.

+3
source share

You can create appropriate java classes for json objects. Integer, string values ​​can be displayed as is. Json can be parsed as follows:

  Gson gson = new GsonBuilder().create(); Response r = gson.fromJson(jsonString, Response.class); 

Here is an example - http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

+1
source share

I do not know if GSON can perform streaming / incremental binding (I thought it wasn’t).

But is there a specific reason to just consider this particular library? Other Java JSON processing libraries allow this processing (you can check the links that another answer has for some ideas), since this is a very important function when processing large channels.

0
source share

All Articles