This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?
In Groovy, it's a matter of few lines of code. Java examples that I find are ridiculously long (and have huge exception handling block).
All I want to do is to read the content of this link.
I am not sure if this is efficient, but this is one of the possible ways:
Read json from url use
url.openStream()
and read contents into a string.construct a JSON object with this string (more at json.org)
The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/
Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)
If you don't mind using a couple libraries it can be done in a single line.
Include Apache Commons IOUtils & json.org libraries.
Use HttpClient to grab the contents of the URL. And then use the library from json.org to parse the JSON. I've used these two libraries on many projects and they have been robust and simple to use.
Other than that you can try using a Facebook API java library. I don't have any experience in this area, but there is a question on stack overflow related to using a Facebook API in java. You may want to look at RestFB as a good choice for a library to use.
It's very easy, using jersey-client, just include this maven dependency:
Then invoke it using this example:
Then use Google's Gson to parse the JSON:
Using the Maven artifact
org.json:json
I got the following code, which I think is quite short. Not as short as possible, but still usable.