Reputation: 2423
I am currently trying to parse through a the front page of Reddit using their cool website feature in which you can add /.json to any site to get the json of the page. So the url I am using is www.reddit.com/.json.
I want to get the subreddit of the first post by parsing through their json. How would I do this? I did some research and found the google gson api but I have no idea how to use it and their documentation does not really help me.
Here is my code so far, I have the Json in a string:
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 inputLine = null;
StringBuilder sb = new StringBuilder();
try {
while ((inputLine = in.readLine()) != null){
sb.append(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputLine = sb.toString();//String of json
System.out.println(inputLine);
//I want to get [data][children][data][subreddit]
}
}
Upvotes: 1
Views: 791
Reputation: 18741
You can create this class structure to parse your response (in pseudo-code):
class Response
Data data
class Data
List<Child> children
class Child
OtherData data
class OtherData
String subreddit
Then you parse your JSON string with:
Gson gson = new Gson();
Response response = gson.fromJson(inputLine, Response.class);
And in order to get the concrete data you need, just:
String subreddit = response.getData().getChildren().getOtherData().getSubreddit();
Note that you can change the names of the classes, but NOT the names of the attributes, since they have to match the names in the JSON response!
Also note that I have only added the attributes you need to get that concrete data, but if you add more attributes in the classes, matching the element names in the JSON, more data will be parsed...
Further similar examples here, here or here.
Finally note that you can make your classes nested to keep your project cleaner, but if however you don't like to write so many classes, and you are sure that you only want that specific value and you won't want any value else in the future, you can use this different approach, although I don't recommend it...
Upvotes: 3