如何通过键获取嵌套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()onrootobj.get("data"), which turned the JSON object into a plain string—you lost the structured access to nested fields. Instead, we keep it as aJsonObjectwithgetAsJsonObject("data"). - Access nested arrays: The
childrenfield is a JSON array, so we usegetAsJsonArray("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, avoidingIndexOutOfBoundsException. - Handle edge cases: We check if the
childrenArrayis 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
childrenarray is an object with its owndatafield—we access that, then pull out specific fields likesubredditusinggetAsString().
Notes
- Make sure you have the Gson library added to your project (this is what the
JsonParserand related classes come from). - Reddit's API requires a valid
User-Agentheader, which your original code already included—don't remove that, or you'll get a 403 Forbidden error.
内容的提问来源于stack exchange,提问作者Luke Prior
相关产品推荐
相关产品推荐

