user1798578 user1798578 - 3 months ago 12
Java Question

How to Parse JSON Response in JAVA

Im having trouble retrieving the temperature from the json code below using java. I'm able to retrieve the location but when I try to get the temperature i'm receiving the error

JSONObject["temp"] not a string.


Can someone please help me with this problem.

URL url1 = new URL(urlJson);
connection = (HttpURLConnection)url1.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset);
connection.connect();

responseCode = connection.getResponseCode();

InputStream response = connection.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(response, writer, "utf-8");
String theString = writer.toString();
System.out.println("THE STRING"+theString);

JSONObject obj = new JSONObject(theString);

String location = obj.getString("name");
System.out.println("The location is -"+location);

String temp = obj.getString("temp");
System.out.println("The current temperature is -"+temp);


JSON code

{
"coord":{
"lon":-83.45,
"lat":39.89
},
"sys":{
"type":1,
"id":2164,
"message":0.004,
"country":"US",
"sunrise":1472036117,
"sunset":1472084182
},
"weather":[
{
"id":800,
"main":"Clear",
"description":"sky is clear",
"icon":"01n"
}
],
"base":"stations",
"main":{
"temp":17.8,
"pressure":1023,
"humidity":88,
"temp_min":16,
"temp_max":19.44
},
"visibility":16093,
"wind":{
"speed":3.6,
"deg":170
},
"clouds":{
"all":1
},
"dt":1472028028,
"id":4517009,
"name":"London",
"cod":200
}

Answer

You need to change your function to .getDouble temp is not returning as a string value type.

So ıt should be like:

obj.getJSONObject("main").getDouble("temp")

I edit the answer.

Comments