簡體   English   中英

我在這個解析中做錯了什么?

[英]What am I doing wrong in this parsing?

我目前通過解析reddit.com/.json與谷歌GSON並遇到了一些麻煩。 在做了一些研究后,我找到了一種方法來解析json與Gson,而不需要進行大量的課程。 我正在使用這種方法 到目前為止,這是我的代碼:

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

}

您正在嘗試將元素"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"數組的第一個元素的數據,因為它似乎是您想要查看代碼並主要查看您的其他問題

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());
    }
}
  1. 您不需要為每個可以引發異常的表達式創建try..catch塊。
  2. JsonParser.parse()方法接受Reader (例如InpustStreamReader )實例,因此您不必自己讀取JSON。
  3. root[data][children]是一個對象數組,因此您必須對它們進行迭代才能獲得對單個對象的訪問權限。
  4. 我相信你想把所有[subredit]讀成某種集合, Set I pressume?

     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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM