1

我目前正在使用 Google Gson 解析reddit.com/.json并且遇到了一些麻烦。在做了一些研究之后,我找到了一种使用 Gson 解析 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 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);
    }

}
4

3 回答 3

2

您试图将元素"children"作为 a JsonObject,但它是 aJsonArray因为它被[ ]...

尝试这样的事情:

JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();

//Here is the change
JsonObject locObj = rootObj
                      .getAsJsonObject("data")
                      .getAsJsonArray("children")
                      .get(0)
                      .getAsJsonObject()
                      .getAsJsonObject("data");

String subreddit = locObj.get("subreddit").getAsString();

注意:我假设您只想获取"children"数组的第一个元素的数据,因为它似乎是您想要查看代码并主要查看您的另一个问题的内容

于 2013-05-17T12:48:01.343 回答
1

children对象返回一个Array您必须迭代的对象。

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();
    JsonArray locObj = rootObj.getAsJsonObject("data").getAsJsonArray("children");

    /* Iterating children object */
    Iterator<JsonElement> iterator = locObj.iterator();

    while(iterator.hasNext()){
        JsonElement element = iterator.next();
        JsonElement subreddit = element.getAsJsonObject().getAsJsonObject("data").get("subreddit");
        System.out.println(subreddit.getAsString());
    }
}
于 2013-05-17T12:51:38.207 回答
1
  1. 您不需要try..catch为每个可能引发异常的表达式创建块。
  2. JsonParser.parse()方法接受Reader(例如InpustStreamReader)实例,因此您不必自己阅读 JSON。
  3. root[data][children]是一个对象数组,因此您必须遍历它们才能访问单个对象。
  4. 我相信您想将所有[subredit]s 读入某种集合中,Set我想?

    public static void main(String[] args) {
        try {
            Set<String> subreddits = new HashSet<>();
            URL url = new URL("http://www.reddit.com/.json");
    
            JsonParser parser = new JsonParser();
            JsonObject root = parser.parse(new InputStreamReader(url.openConnection().getInputStream())).getAsJsonObject();
            JsonArray children = root.getAsJsonObject("data").getAsJsonArray("children");
    
            for (int i = 0; i < children.size(); i++) {
                String subreddit = children.get(i).getAsJsonObject().getAsJsonObject("data").get("subreddit").getAsString();
                subreddits.add(subreddit);
            }
    
            System.out.println(subreddits);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

此代码返回:

[IAmA, worldnews, technology, news, todayilearned, gaming, AskReddit, movies, videos, funny, bestof, science, WTF, politics, aww, pics, atheism, Music, AdviceAnimals]
于 2013-05-17T12:57:33.910 回答