使用谷歌Gson解析Json Feed [英] Parsing Json Feeds with google 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 =新网址(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屋!