2013-05-17 68 views
1

我目前正在嘗試使用他們酷的網站功能來解析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] 
} 

}

回答

3

您可以創建這個類的結構來分析你的迴應(在僞代碼):

class Response 
    Data data 

class Data 
    List<Child> children 

class Child 
    OtherData data 

class OtherData 
    String subreddit 

然後,解析您的JSON字符串:

Gson gson = new Gson(); 
Response response = gson.fromJson(inputLine, Response.class); 

而且爲了得到你所需要的具體數據,只是:你可以改變類的名稱

String subreddit = response.getData().getChildren().getOtherData().getSubreddit(); 

注意,而不是屬性的名稱,因爲它們具有相匹配的名字在JSON響應中!

另外請注意,我只加了你需要得到具體數據的屬性,但如果你在類增加更多的屬性,匹配的JSON元素名稱,更多的數據將被解析...

其他類似示例here,herehere

最後要說明的是,你可以讓你的類嵌套來保持你的項目更清潔,但是如果你不喜歡寫這麼多的類,並且你確定你只想要這個特定的值而你不想要任何其他值在未來,您可以使用this different approach,雖然我不推薦它...

相關問題