1

我目前正在尝试使用他们很酷的网站功能解析 Reddit 的首页,您可以在其中将 /.json 添加到任何站点以获取页面的 json。所以我使用的网址是 www.reddit.com/.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]
}

}

4

1 回答 1

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 中的元素名称,将解析更多数据......

更多类似的例子在这里这里这里

最后请注意,您可以使您的类嵌套以使您的项目更清洁,但是如果您不喜欢编写这么多的类,并且您确定您只想要那个特定的值并且您不会想要任何其他值未来,你可以使用这种不同的方法,虽然我不推荐它......

于 2013-05-17T00:20:19.427 回答