【问题标题】:What am I doing wrong in this parsing?我在这个解析中做错了什么?
【发布时间】:2013-05-17 12:36:07
【问题描述】:

我目前正在使用 Google Gson 解析 reddit.com/.json,但遇到了一些问题。在做了一些研究之后,我找到了一种使用 Gson 解析 json 的方法,而无需制作很多类。我正在使用这个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);
    }

}

【问题讨论】:

  • 我会评论说,如果您不使用来自 gson 的自动序列化元素,那么您还不如使用来自 json.org 的较小的 jar。它提供像 JsonObject 这样的低级对象,并且是一个较小的依赖项。

标签: java json gson


【解决方案1】:

您正试图将元素 "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" 数组的第一个元素的数据,因为看起来它是您想要查看代码并且主要查看this other question of yours 的内容。

【讨论】:

    【解决方案2】:

    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());
        }
    }
    

    【讨论】:

      【解决方案3】:
      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]
      

      【讨论】:

        猜你喜欢
        • 2016-04-04
        • 1970-01-01
        • 1970-01-01
        • 2018-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多