使用谷歌Gson解析Json Feed [英] Parsing Json Feeds with google Gson

查看:126
本文介绍了使用谷歌Gson解析Json Feed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何按项目解析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 =新网址(addr);
IOUtils.copy(url.openStream(),output);
return output.toString();
}
}


解决方案

取决于在实际的JSON格式。实际上,您可以创建一个与JSON格式匹配的自定义Javabean类。 JSON中的任何字段都可以映射为字符串整数布尔值等Javabean属性。任何数组都可以映射为 List 属性。任何对象都可以映射为另一个嵌套的Javabean属性。它大大简化了Java中的进一步处理。



如果没有JSON字符串示例,只能猜测它的外观,所以我不能举一个基本示例这里。但在此之前,我发布了类似的答案,您可能会发现它很有用:



Gson也有用户指南,您可能会觉得它很有用还有。

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解析Json Feed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆