Accessing rain from returned openweathermap json data - java

This is my JSON,
{
"city": {
"id": 2961297,
"name": "Swords",
"coord": {
"lon": -6.21806,
"lat": 53.459721
},
"country": "IE",
"population": 0
},
"cod": "200",
"message": 0.3535,
"cnt": 1,
"list": [
{
"dt": 1481025600,
"temp": {
"day": 284.68,
"min": 284.68,
"max": 285.36,
"night": 285.36,
"eve": 284.8,
"morn": 284.68
},
"pressure": 1028.26,
"humidity": 95,
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"speed": 9.01,
"deg": 186,
"clouds": 92,
"rain": 0.5
}
]
}
I am trying to access the rain value "rain": 0.5 as seen in the returned JSON data above I am unsure how exactly to do this as I don't have much experience working with JSON data.
This is my code,
JSONObject topLevel = new JSONObject(builder.toString());
JSONArray ListArray = topLevel.getJSONArray("list");
weather = String.valueOf(ListArray);
for(int x = 0;x < ListArray.length();x++) {
JSONObject myObj = ListArray.getJSONObject(x);
myObj.getInt("rain");
Log.d("TODAYS Rain"+rain,"");
//System.out.Print("Current Weather" +id+main+icon+dscription+rain);
}
Any help is greatly appreciated.

JSONObject topLevel = new JSONObject(builder.toString());
JSONArray listArray = topLevel.getJSONArray("list");
JSONObject firstObject = (JSONObject)listArray.get(0);
Double rain = firstObject.getDouble("rain");
System.out.println("TODAYs rain :" + rain);
}

The easiest way is to parse a Json is to use POJO classes that map the Json into an object instance.
You define the class structure and it gets filled with the data retrieved.
There is a guide on that same topic on this website: http://www.ssaurel.com/blog/learn-how-to-parse-json-in-android-with-gson/

JSONObject topLevel = new JSONObject(builder.toString());
JSONArray ListArray = topLevel.getJSONArray("list");
weather = String.valueOf(ListArray);
for(int x = 0;x < ListArray.length();x++) {
JSONObject myObj = ListArray.getJSONObject(x);
myObj.getDouble("rain");
Log.d("TODAYS Rain"+rain,"");
//System.out.Print("Current Weather" +id+main+icon+dscription+rain);
}
You just need to use myobj.getDouble("rain") instead of myobj.getInt("rain") as the value of rain is not integer.

Related

Want to read JSONArray with JSONObject, but got the error A non-empty JSON Pointer

My Json FILE (it´s an array! )
[
{
"datasetid": "country-flags",
"recordid": "d661d0a8676bf4d7563114c1d9c465987df22132",
"fields": {
"num_un": 32,
"geolocation": [
-38.416097,
-63.616672
],
"dialing_code": "54",
"a3_un": "ARG",
"country": "Argentina",
"flag": {
"mimetype": "image/png",
"format": "PNG",
"filename": "ar.png",
"width": 16,
"id": "fceb4235ce95c8597bfa77d0db0181a0",
"height": 11,
"thumbnail": true
},
"a2_iso": "AR"
},
"geometry": {
"type": "Point",
"coordinates": [
-63.616672,
-38.416097
]
},
"record_timestamp": "2016-09-26T07:48:38.162+02:00"
},
more...
]
So i want to get the value from coordinates. So for this i tried to work with this:
JsonReader jsonReader = Json
.createReader(new FileReader(getClass().getResource("country-flags.json").getPath()));
JsonArray arr = jsonReader.readArray();
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
System.out.println("coordinates: " + obj.containsKey("\"coordinates\""));
System.out.println("##########");
System.out.println(obj.getValue("\"coordinates\""));
}
But i got the error:
javax.json.JsonException: A non-empty JSON Pointer must begin with a
'/'
Can someone help me out ?!
Your code obj.containsKey("\"coordinates\"") will return false as coordinates is NOT a top level key, but is a 2nd level (nested) key. If you print obj.keySet(), you will get [datasetid, recordid, fields, geometry, record_timestamp] (first / top level keys only).
If the structure of your JSON is fixed, you can use the following code:
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
JsonObject jsonChildObject = obj.getJsonObject("geometry");
if(jsonChildObject.containsKey("coordinates"))
System.out.println(jsonChildObject.getValue("/coordinates"));
}
Notice the / in front of the getValue method's coordinates param. I think that was the reason you were here in the first place.

How do I get a value greater than a specified value in rest assured

I am a newbie to Rest-Assured api using Java. I want to extract the number of days the temperature of a city is above 18 . Using openweathermap.org.
The url is api.openweathermap.org/data/2.5/forecast?q=Sydney&units=metric&appid={APP KEY}
I get :
{
"cod": "200",
"message": 0.0067,
"cnt": 40,
"list": [
{
"dt": 1557727200,
"main": {
"temp": 20.88,
"temp_min": 20.88,
"temp_max": 21.05,
"pressure": 1025.56,
"sea_level": 1025.56,
"grnd_level": 1021.14,
"humidity": 57,
"temp_kf": -0.17
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"clouds": {
"all": 55
},
"wind": {
"speed": 3.45,
"deg": 43.754
},
"sys": {
"pod": "d"
},
"dt_txt": "2019-05-13 06:00:00"
},
{
"dt": 1557738000,
"main": {
"temp": 18.45,
"temp_min": 18.45,
"temp_max": 18.58,
"pressure": 1026.06,
"sea_level": 1026.06,
"grnd_level": 1021.28,
"humidity": 73,
"temp_kf": -0.13
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04n"
}
],
"clouds": {
"all": 100
},
"wind": {
"speed": 3.84,
"deg": 28.267
},
"sys": {
"pod": "n"
},
"dt_txt": "2019-05-13 09:00:00"
}, {
"dt": 1557759600,
"main": {
"temp": 14.31,
"temp_min": 14.31,
"temp_max": 14.35,
"pressure": 1026.29,
"sea_level": 1026.29,
"grnd_level": 1021.87,
"humidity": 80,
"temp_kf": -0.04
},
"weather": [
{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03n"
}
],
"clouds": {
"all": 28
},
"wind": {
"speed": 1.66,
"deg": 279.19
},
"sys": {
"pod": "n"
},
"dt_txt": "2019-05-13 15:00:00"
},
}
I am unsure how do i proceed with the iterations. It would be a great help if someone can help me through.
I am able to get the data but not sure how do I get the element from each array
Now, I want to extract the temperatures which are above 18 degrees
I have attempted the below:
public class WeatherForecast {
public static Response resp;
#Test
public void getWeatherForecastForCity()
{
RestAssured.baseURI = "https://api.openweathermap.org";
resp = given().
param("q", "Sydney").
param("units", "metric").
param("appid", "670473f82ba0969a884be548c75236a4").
when().
get("/data/2.5/forecast").
then().
extract().response();
List<String> temperatures = resp.getBody().jsonPath().getList("list");
//String value = temperatures.getString()
int count = temperatures.size();
for(int i=0;i<=count;i++)
{
}
System.out.println("List Size: "+temperatures.size());
//assertEquals(temperatures, greaterThanOrEqualTo(20.00F));
//String responseString = resp.asString();
//System.out.println("Response String: "+responseString);
//JsonPath js = new JsonPath(responseString);
//Get the number of records for the city
//int size = js.getList("list").size();
//int temperature = Integer.parseInt(js.get("count"));
//System.out.println("Temperature Value: "+js.getString("list[1].main.temp"));
}
}
RestAssureduses a powerful library called JsonPath which you already used.
The difference of what you already creates is how to get JSONObject/Array inside other JSONObject/Array
You used resp.getBody().jsonPath().getList("list"); which is almost a good starting point. Instead of using List<String> you should use List<HashMap<String, Object>>
Each HashMap<> will be a JSON Object.
Then you can just iterate over the Array to get each object and temperatures.
How to do that:
List<HashMap<String, Object>> list = resp.getBody().jsonPath().getList("list");
for (HashMap<String, Object> jsonObject : list) {
/**
* Now, in order to get temperature, we have to get access to `main` element in JSON and then get access to the temperature
**/
HashMap<String, Object> mainElements = (HashMap<String, Object>) jsonObject.get("main");
//No we have JSONObject as HashMap. We can access any temperature
float temperature = (float) mainElements.get("temp");
System.out.println(temperature);
}
The above code will print all temperatures. Now you just have to compare float values, save them, assert them or do whatever you want :)
You can access any value with this approach
EDIT:
Extract the above code to a method like this:
private List<HashMap<String, Object>> getJsonObjectsWithTempGreaterThan(JsonPath path, float degrees) {
List<HashMap<String, Object>> desiredJsonObjects = new ArrayList<>();
List<HashMap<String, Object>> list = path.getList("list");
for (HashMap<String, Object> jsonObject : list) {
HashMap<String, Object> mainElements = (HashMap<String, Object>) jsonObject.get("main");
float temperature = (float) mainElements.get("temp");
if (temperature > degrees) {
desiredJsonObjects.add(jsonObject);
}
}
return desiredJsonObjects;
}
Above code will store each of JSON Object in a List and then return it. The list will contain JSON Objects with a temperature greater than degrees passed in the parameter.
Then, you can access those elements like this:
List<HashMap<String, Object>> objects = getJsonObjectsWithTempGreaterThan(path, 20);
This is our list of desired objects.
If you just want the temperatures, all you have to do is:
for (HashMap<String, Object> jsonObject : objects) {
HashMap<String, Object> mainElements = (HashMap<String, Object>) jsonObject.get("main");
//No we have JSONObject as HashMap. We can access any temperature
float temperature = (float) mainElements.get("temp");
System.out.println(temperature);
}
This can be achieved much more easily and readable with Java Streams.

Android time and string

in my app i recevie char sequence thats from sql something like this:
"{"1":{"from":"540","to":"1020"},"2":{"from":"540","to":"1020"},"3":{"from":"540","to":"1020"},"4":{"from":"540","to":"1020"},"5":{"from":"540","to":"1020"},"6":{"from":"540","to":"1020"},"7":{"from":"540","to":"1020"}}"
This is full week, day by day and minutes since midnight. I have idea how to use it but i don't know right now how to crop it on sense strings which should be looks like:
String monday_open = 540;
String monday_close = 1020;
and same to the end of the week
Maybe somebody know easy way to crop this sequence?
this
"{"1":{"from":"540","to":"1020"},"2":{"from":"540","to":"1020"},"3":{"from":"540","to":"1020"},"4":{"from":"540","to":"1020"},"5":{"from":"540","to":"1020"},"6":{"from":"540","to":"1020"},"7":{"from":"540","to":"1020"}}"
is a json Text
my json String
{
"coord": {
"lon": 51.42,
"lat": 35.69
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"base": "cmc stations",
"main": {
"temp": 298.45,
"pressure": 1016,
"humidity": 39,
"temp_min": 298.15,
"temp_max": 299.15
},
"wind": {
"speed": 2.1,
"deg": 240
},
"clouds": {
"all": 40
},
"dt": 1439151053,
"sys": {
"type": 1,
"id": 7032,
"message": 0.0034,
"country": "IR",
"sunrise": 1439084924,
"sunset": 1439134215
},
"id": 112931,
"name": "Tehran",
"cod": 200
}
and i parse it with method blew:
private void jsonRead(String file) throws JSONException {
JSONObject root=new JSONObject(file);
JSONArray jsonArray = root.optJSONArray("weather");
JSONObject jo2=root.optJSONObject("main");
for(int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
dama.setText(jsonObject.getString("description"));
}
rotobat.setText(jo2.getString("humidity"));
}

get JsonObject without knowing its name Java

I have this JSON I need to parse. Its format looks something likes this:
{
"47M": [
{
"lat": 39.95507,
"lng": -75.152122,
"label": 8011,
"VehicleID": 8011,
"BlockID": 7995,
"Direction": "NorthBound",
"destination": "Spring Garden via 9th St.",
"Offset": 1,
"Offset_sec": 29
},
{
"lat": 39.913765,
"lng": -75.155464,
"label": 8038,
"VehicleID": 8038,
"BlockID": 7993,
"Direction": "NorthBound",
"destination": "Spring Garden via 9th St.",
"Offset": 3,
"Offset_sec": 158
}
]
}
However, that "47M" can be "5", "H", "101", etc. And I need to get those "5", "H", etc.
I believe I should use the loop for (obj : root) , but I don't know what's the type for obj
You could use simple json (https://code.google.com/p/json-simple/) Library and code like this to iterate over the keys.
JSONParser parser = new JSONParser();
jObject = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) jObject;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}

how to get the value of lat and lng from the json

I have a json response.I want to get the value of lat and lng from the json response.But i didn't get the values.Please Help me.Below is my response.
{
"html_attributions": [],
"results": [
{
"geometry": {
"location": {
"lat": 9.493837,
"lng": 76.338506
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "2730a3d7ab068d666e61a02ce6160b4cd21a38c7",
"name": "Nagarjuna",
"place_id": "ChIJr0-U4vSECDsRtiALUlgZOzI",
"reference": "CmRcAAAA4yl72_x5llqvdshRJwuuntunXrYu33qdP5G7-I0CdHzcDsyd6wwqjxdNeqvT6vtRIoDoIk_WGNd62SYSoNEdBrpDrOcf5g5eZMj_vobhmF11mrujsQ_Yc7p-oGxQH0XtEhDNJdjQf_WlK_dRAckBzlA3GhQ_wzXs5RxoaxWDSEurm_R5syuovg",
"scope": "GOOGLE",
"types": [
"hospital",
"establishment"
],
"vicinity": "State Highway 40, Kodiveedu, Alappuzha"
},
{
"geometry": {
"location": {
"lat": 9.500542,
"lng": 76.341017
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "d5b6c81a53a346dea1263de7a777703bc72b8796",
"name": "SYDNEY OPTICALS",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 422,
"html_attributions": [],
"photo_reference": "CnRnAAAA_jg-NlSrVKkDOP7wXhPhvFTD8NW4A4aDI_Ptl3F9c_qt9QwdztNTG9Cr51uGIphpEUMyhsTfhhaa-TlfoL8MUEffbguZJ1AhKUwzfe7Mbrvm2KW8Y1EQXVw_3FglxA4LM1hqWJCK_AV4xcvOw1vuHRIQ8_keBYr29H8jK145RQ_PkRoUgPZ0qzcSNdIntc2ZI4WvBIR-TBQ",
"width": 630
}
],
"place_id": "ChIJl9tvIV6ECDsR7Cmf3KkIl-4",
"reference": "CnRjAAAA3qhFUcb8P9akE8xw-KwfF6OU6qvy2cVX4Sg0qK_xCOfeUEyxoFgwof8rk-Z2BBJ7Z4m7ZTbfdp78wqFbeLfojQWPldq7XDfzX0pLScBSysebEp9P4XmrsAO5qyqSUveb5jWcJDkYiOLKgaKMzoWQphIQbldrdJ9iEDHkGiQ7tleNYxoUnjcjcynUDMftaErRUQbOn-GkWj0",
"scope": "GOOGLE",
"types": [
"store",
"hospital",
"health",
"establishment"
],
"vicinity": "Mullakkal, Alappuzha"
}
],
"status": "OK"
}
This is the google api response i used for getting the list of hospitals.Anybode plese help me.Thanks in advance.
Use these steps:
Create a model class for that Json Response
Use Gson to parse the response
Then create an object of the class
using the object get the data variable from the class
I hope I can help.
First, validate your JSON with http://jsonlint.com/
Second, use this site to generate POJO: http://www.jsonschema2pojo.org/
make sure that Annotation GSON and Source type JSON are clicked ON!
Copy your classes in to your project.
Third: use GSON in Android :) (Retrofit is good for this)
Supposing you use the json.org Implementation for Java:
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject jo = new JSONObject(response);
JSONObject result = jo.getJSONArray("results").getJSONObject(0);
JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
try this
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject objResponce = new JSONObject(response);
JSONArray arrayResults=new JSONArray(objResponce.getString("results"));
if(arrayResults.length()>0)
{
for(int i=0;i<arrayResults.length();i++)
{
//--- get each json object from array -----
JSONObject objArrayResults = arrayResults.getJSONObject(i);
//--- get geometry json object from each object of array -----
JSONObject objGeometry=new JSONObject(objArrayResults.getString("geometry"));
//--- get location json object from geometry json object -----
JSONObject objLocation=new JSONObject(objGeometry.getString("location"));
System.out.println("Latitude :"+objLocation.getString("lat"));
System.out.println("Longitude :"+objLocation.getString("lng"));
}
}

Categories