简体   繁体   中英

What am I doing wrong in this parsing?

I am currently parsing through reddit.com/.json with Google Gson and having some trouble. After doing some research I found a way to parse through json with Gson without making a lot of classes. I am using this method . Here is my code so far:

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

}

You are trying to get the element "children" as a JsonObject , but it is a JsonArray because it is surrounded by [ ] ...

Try something like this:

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

Note: I assume that you only want to get the data of the first element of the "children" array, since it seems that it is what you want looking at your code and mainly looking at this other question of yours .

The children object returns an Array that you must iterate.

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. You don't need to create try..catch block for every expression that can throw an exception.
  2. JsonParser.parse() method accepts Reader (eg InpustStreamReader ) instance so you don't have to read JSON on your own.
  3. root[data][children] is an array of objects so you'll have to iterate over them in order to gain access to individual objects.
  4. I believe you want to read all [subredit] s into some sort of collection, 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(); } } 

This code returns:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM