Parsing Json Feeds with google Gson

假装没事ソ 提交于 2019-12-12 09:38:40

问题


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();
    }
}   

回答1:


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.




回答2:


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




回答3:


You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-

 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




回答4:


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.



来源:https://stackoverflow.com/questions/2034643/parsing-json-feeds-with-google-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!