我在这个解析中做错了什么?

时间:2013-05-17 12:36:07

标签: java json gson

我目前正在使用Google Gson解析reddit.com/.json并遇到一些麻烦。在做了一些研究后,我找到了一种方法来解析json与Gson,而不需要进行大量的课程。我正在使用此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);
    }

}

3 个答案:

答案 0 :(得分:2)

您正在尝试将元素"children"作为JsonObject,但它是JsonArray,因为它被[ ]包围...

尝试这样的事情:

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"数组的第一个元素的数据,因为它似乎是您想要查看代码并主要查看{{ 3}}

答案 1 :(得分: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());
    }
}

答案 2 :(得分:1)

  1. 您不需要为每个可以抛出异常的表达式创建try..catch块。
  2. JsonParser.parse()方法接受Reader(例如InpustStreamReader)实例,因此您无需自行阅读JSON。
  3. root[data][children]是一个对象数组,因此您必须对它们进行迭代才能获得对单个对象的访问权。
  4. 我相信你想把所有的[subredit]读成某种集合,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();
        }
    }
    
  5. 此代码返回:

    [IAmA, worldnews, technology, news, todayilearned, gaming, AskReddit, movies, videos, funny, bestof, science, WTF, politics, aww, pics, atheism, Music, AdviceAnimals]