我目前正在嘗試使用他們酷的網站功能來解析Reddit的首頁,您可以在其中添加/.json到任何網站以獲取頁面的json。所以我使用的網址是www.reddit.com/.json。如何使用Google的Gson從JSON響應中獲取特定值?
我想通過解析他們的json來獲得第一篇文章的subreddit。我將如何做到這一點?我做了一些研究,發現了google gson api,但我不知道如何使用它,他們的文檔並沒有真正幫助我。
這是到目前爲止我的代碼,我將JSON字符串中的:
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 inputLine = null;
StringBuilder sb = new StringBuilder();
try {
while ((inputLine = in.readLine()) != null){
sb.append(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputLine = sb.toString();//String of json
System.out.println(inputLine);
//I want to get [data][children][data][subreddit]
}
}