I have the following code which I use to download a JSON file from a URL:
static void getPost() throws Exception {
String webPage = "https://www.reddit.com/r/arabfunny/top.json?limit=100";
URL url = new URL(webPage);
URLConnection request = url.openConnection();
request.setRequestProperty("Content-Type", "application/json; utf-8");
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");
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
String imageURL = rootobj.get("data").toString();
System.out.println(imageURL);
}
This correctly gets the code but I'm having trouble getting data past the first level, I can use .get("data")
and that works as expected but I cannot do .get("data").get("children")
.
The JSON file can be found here.
Here is the JSON prettyfied.
I want to get a random children where I don't know the number of children. Something like rootobj.get("data").get("children").get(RANDOM).toString();
EDIT:
I really just need a simple solution to get a few parameters from a random children.
I need to get JSON -> data -> children[random item] -> data -> subreddrit (or other final field)
Can anyone show me a basic working example that would give me any final value which I can then modify?