I am using a HttpURLConnection
to get Json
from a web into a string.
And i'm storing web string into BufferedReader
and after that storing it in a new String
.
And string is here:-
{"coord":{"lon":72.85,"lat":19.01},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":302.131,"pressure":1024.24,"humidity":84,"temp_min":302.131,"temp_max":302.131,"sea_level":1024.75,"grnd_level":1024.24},"wind":{"speed":4.77,"deg":302.001},"clouds":{"all":12},"dt":1459677392,"sys":{"message":0.0102,"country":"IN","sunrise":1459645229,"sunset":1459689786},"id":1275339,"name":"Mumbai","cod":200}
How can i convert it into JsonObject.
I've also seen this answer ( How to convert String to JsonObject ) but it's not working.
Here is code:-
BufferedReader br= new BufferedReader(new InputStreamReader(conn.getInputStream()));
String localoutput;
while ((localoutput = br.readLine()) != null)
{
output=localoutput+output;
}
conn.disconnect();
}
catch(Exception e)
{
System.out.println(e);
}
JsonReader jsonReader = Json.createReader(new StringReader(output));
JsonObject object = jsonReader.readObject();
jsonReader.close();
try {
String cityname = object.getString("name");
System.out.println(cityname);
}
catch (Exception e)
{
e.printStackTrace();
}
Here output is the String which I've mentioned it earlier. I'm not getting the Output Cityname in my console.
Use this library. It provides very simple API, to convert a String to json object simply do the following:
try {
JSONObject object = new JSONObject(yourJsonString);
} catch (Exception e){
e.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.