用谷歌Gson解析Json Feeds

Roc*_*och 7 java parsing json gson

我想知道如何通过项目解析JSON提要(例如,每个项目的url/title/description).我看过doc/api,但它没有帮助我.

这是我到目前为止所得到的

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();
    }
}   
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 9

取决于实际的JSON格式.实际上,您可以创建一个与JSON格式匹配的自定义Javabean类.在JSON任何字段可以被映射为String,Integer,Boolean等JavaBean属性.任何数组都可以映射为List属性.任何对象都可以映射为另一个嵌套的Javabean属性.它极大地简化了Java中的进一步处理.

没有你身边的JSON字符串示例,它只是猜测它会是什么样子,所以我不能在这里给出一个基本的例子.但是我在此之前发布了类似的答案,你可能会发现它很有用:

Gson还有一个用户指南,您可能会发现它也很有用.