You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过键获取嵌套JSON内容?Java实现随机子项字段提取

Fixing Nested JSON Access & Random Child Selection in Java

Let's get your code working properly to access those nested Reddit JSON fields and pick a random child post. Here's a complete, runnable example with explanations:

Full Working Code

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class RedditPostFetcher {
    public static void main(String[] args) {
        try {
            getRandomTopPost();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static void getRandomTopPost() throws Exception {
        String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";
        URL url = new URL(webPage);
        URLConnection request = url.openConnection();
        
        // Set required headers (Reddit blocks requests without a User-Agent)
        request.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        
        // Parse the JSON response
        JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
        JsonObject rootObj = root.getAsJsonObject();

        // Access the nested "data" object, then get the "children" array
        JsonObject dataObj = rootObj.getAsJsonObject("data");
        JsonArray childrenArray = dataObj.getAsJsonArray("children");

        // Handle empty array case to avoid errors
        if (childrenArray.size() == 0) {
            System.out.println("No posts found!");
            return;
        }

        // Pick a random index from the children array
        Random random = new Random();
        int randomIndex = random.nextInt(childrenArray.size());
        JsonElement randomChild = childrenArray.get(randomIndex);

        // Extract the post's data object from the random child
        JsonObject postData = randomChild.getAsJsonObject().getAsJsonObject("data");

        // Extract desired fields (subreddit, title, url, etc.)
        String subreddit = postData.get("subreddit").getAsString();
        String title = postData.get("title").getAsString();
        String postUrl = postData.get("url").getAsString();

        // Print the results
        System.out.println("Random Post from r/" + subreddit + ":");
        System.out.println("Title: " + title);
        System.out.println("URL: " + postUrl);
    }
}

Key Fixes & Explanations

  • Don't convert JSON elements to strings early: Your original code called toString() on rootobj.get("data"), which turned the JSON object into a plain string—you lost the structured access to nested fields. Instead, we keep it as a JsonObject with getAsJsonObject("data").
  • Access nested arrays: The children field is a JSON array, so we use getAsJsonArray("children") to retrieve it, then work with its elements directly.
  • Random selection: We use Random.nextInt(childrenArray.size()) to get a valid index within the array bounds, avoiding IndexOutOfBoundsException.
  • Handle edge cases: We check if the childrenArray is empty before trying to pick a random element, so your code won't crash if there are no posts returned.
  • Extract final fields: Each child in the children array is an object with its own data field—we access that, then pull out specific fields like subreddit using getAsString().

Notes

  • Make sure you have the Gson library added to your project (this is what the JsonParser and related classes come from).
  • Reddit's API requires a valid User-Agent header, which your original code already included—don't remove that, or you'll get a 403 Forbidden error.

内容的提问来源于stack exchange,提问作者Luke Prior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:37:39