【发布时间】:2013-05-17 12:36:07
【问题描述】:
我目前正在使用 Google Gson 解析 reddit.com/.json,但遇到了一些问题。在做了一些研究之后,我找到了一种使用 Gson 解析 json 的方法,而无需制作很多类。我正在使用这个method。到目前为止,这是我的代码:
import java.io.*;
import java.net.*;
import com.google.gson.*;
public class Subreddits {
public static void main(String[] args) {
URL u = null;
try {
u = new URL("http://www.reddit.com/.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection yc = null;
try {
yc = u.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String json = null;
StringBuilder sb = new StringBuilder();
try {
while ((json = in.readLine()) != null){
sb.append(json);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
json = sb.toString();//String of json
System.out.println(json);
//I want to get [data][children][data][subreddit]
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("data").getAsJsonObject("children").getAsJsonObject("data");
String subreddit = locObj.get("subreddit").getAsString();
System.out.println(subreddit);
}
}
【问题讨论】:
-
我会评论说,如果您不使用来自 gson 的自动序列化元素,那么您还不如使用来自 json.org 的较小的 jar。它提供像 JsonObject 这样的低级对象,并且是一个较小的依赖项。