Get objects json java

How to get JSON object from HTTP request in Java

I’m now trying to get JSON Object with using HTTP request in Java cord. I want to know how I can get response or JSON object in the following cord. Please let me know. (In this program, I try to get Wikipedia categories of the article «New York». )

String requestURL = "http://en.wikipedia.org/w/api.php?action=query&prop=categories&format=json&clshow=!hidden&cllimit=10&titles mt24 mb12">
    javajsonhttprequest
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
asked Aug 10, 2012 at 12:37
1
    Do NOT do this. You will get OOM's if the request is relatively big and it will be very hard to fix.
    – Edison
    May 19, 2013 at 22:46
Add a comment|

4 Answers 4

Reset to default
4

Just 2 lines of code with JSONTokener

JSONTokener tokener = new JSONTokener(wikiRequest.openStream()); JSONObject root = new JSONObject(tokener);

Источник

Simplest way to read JSON from a URL in Java

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.

The exception handling is required as java forces you to handle any exceptions that are declared. What's wrong with exception handling?

If java didn't force you to handle exceptions do you think programs would still run and run well? What if I was asked to input my age into a program and I gave snarfleblagger as my input? Should java allow the program to just execute with no issues? If you don't want to handle exceptions then declare them as being thrown by the methods that they may occur in and watch your program fail when something isn't perfectly right.

Not a dumb question at all. Especially coming from PHP where you can do this with json_decode(file_get_contents($url)); and be done!

12 Answers 12

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.

package so4308554; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.Charset; import org.json.JSONException; import org.json.JSONObject; public class JsonReader < private static String readAll(Reader rd) throws IOException < StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) < sb.append((char) cp); >return sb.toString(); > public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException < InputStream is = new URL(url).openStream(); try < BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = new JSONObject(jsonText); return json; >finally < is.close(); >> public static void main(String[] args) throws IOException, JSONException < JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552"); System.out.println(json.toString()); System.out.println(json.get("id")); >> 

instead of reading character by character you can use readLine() on BufferedReader. This will reduce the number of iterations of while loop.

What for? The readLine function will do the loop then, and I have to concatenate the lines instead of the characters, which is more expensive. That wouldn't keep the code as short as it is now. Furthermore, in JSON notation there is no concept of "lines", so why should I read them as such?

Consider Apache commons-io's IOUtils.toString(InputStream) method. That should save you some lines and responsibility.

Why i am getting this error "The constructor JSONObject(String) is undefined" in the line of JSONObject json = new JSONObject(jsonText); in "readJsonFromUrl" method. @RolandIllig

With GSON, Jackson, Boon, Genson and others, you only need to feed the source: either just URL, or at most InputStream . While code above may be short for org.json usage, make sure to verify other libs available -- there is no need to write more than 1-3 lines of code for this task.

Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

 ObjectMapper mapper = new ObjectMapper(); // just need one // Got a Java class that data maps to nicely? If so: FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class); // Or: if no class (and don't need one), just map to Map.class: Map map = mapper.readValue(url, Map.class); 

And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class); 

Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

I was thinking of java.net.URL but either one works, as well as plenty of other sources ( File , InputStream , Reader , String ).

It should be java.net.URL in the example above, otherwise it will try to parse string 'http://. ' as a json, which will yield an error

@Zotov Yes. Passing String would require contents to be JSON, and not textual encoding of URI/URL to use.

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)

 String sURL = "http://freegeoip.net/json/"; //just a string // Connect to the URL using java's native library URL url = new URL(sURL); URLConnection request = url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode 

Why i'm getting the 'NetworkOnMainThreadException' error? I must user an AsyncTask or there is another way? In this example did you get this error too?

How do i import the jsonParser? I always get the error: 'Error:(69, 9) error: cannot find symbol class JsonParser'

can be simplified and handled in a typesafe way with Gson like: MyResponseObject response = new GsonBuilder().create().fromJson(new InputStreamReader((InputStream) request.getContent()), MyResponseObject.class);

If you don't mind using a couple libraries it can be done in a single line.

JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8"))); 

Do you have any guess on why adding the dependency to the gradle would prevent this app from installing on my Google Pixel XL?

@andrdoiddev - You should ask that as a separate question. It is more general to Apache Commons, Gradle and Android Development.

This is quite old now, but is still a good solution, so just in case @andrdoiddev or anyone else still needs the Gradle dependencies, these are the ones I'm using: compile group: 'org.json', name: 'json', version: '20180813' compile group: 'commons-io', name: 'commons-io', version: '2.6'

Say you are firing multiple requests, saving the json responses to a JSONArray and then writing the JSONArray to a file using FileWriter, then this library DOES NOT ESCAPE double quotes. This makes the file be easily parsed back to JSONArray.

Thanks @Irregardless, looks like json.org re-worked their packages. There is no longer a default reference java implementation on their site. I will update the link to use the first java project in their list of java libraries on their home page json.org as that should work and be compatible as it's a reference implementation.

I have done the json parser in simplest way, here it is

package com.inzane.shoapp.activity; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser < static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() < >public JSONObject getJSONFromUrl(String url) < // Making HTTP request try < // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); >catch (UnsupportedEncodingException e) < e.printStackTrace(); >catch (ClientProtocolException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >try < BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) < sb.append(line + "\n"); System.out.println(line); >is.close(); json = sb.toString(); > catch (Exception e) < Log.e("Buffer Error", "Error converting result " + e.toString()); >// try parse the string to a JSON object try < jObj = new JSONObject(json); >catch (JSONException e) < Log.e("JSON Parser", "Error parsing data " + e.toString()); System.out.println("error on parse data in jsonparser.java"); >// return JSON String return jObj; > > 

this class returns the json object from the url

and when you want the json object you just call this class and the method in your Activity class

String url = "your url"; JSONParser jsonParser = new JSONParser(); JSONObject object = jsonParser.getJSONFromUrl(url); String content=object.getString("json key"); 

here the "json key" is denoted that the key in your json file

this is a simple json file example

Here "json" is key and "hi" is value

This will get your json value to string content.

Источник

Читайте также:  Body text shadow css
Оцените статью