Reputation: 51
Here i have a little trouble with getting item's value from a JSON string using Gson.
First of all the first part of my code is to get an obejct from massive:
String jsonOutput= weatherDataCollect(message);
Gson gson = new Gson();
JsonElement element = gson.fromJson(jsonOutput, JsonElement.class);
JsonObject jsonObject = element.getAsJsonObject();
System.out.println(jsonObject.toString());
JsonArray list = jsonObject.getAsJsonArray("list");
So now if I write:
JsonElement todaysWeather = list.get(0);
I get exactly what I need - this part of json
{"dt":1549281600,"main":{"temp":-0.38,"temp_min":-1.3,"temp_max":-0.38,"pressure":1024.85,"sea_level":1027.5,"grnd_level":1024.85,"humidity":94,"temp_kf":0.91},"weather":[{"id":600,"main":"Snow","description":"небольшой снегопад","icon":"13d"}],"clouds":{"all":92},"wind":{"speed":2.11,"deg":271.5},"snow":{"3h":0.5445},"sys":{"pod":"d"},"dt_txt":"2019-02-04 12:00:00"}
In JSON massive a lot of parts like this. From everyone I need to get value like this 1549281600
and compare with my to find out which one is closer.
The first part of code shoud look like this
long tomorrowTime = getTomorrowUnixTime();
long timeDifference = Integer.MAX_VALUE;
int minDtIndex = 0;
for (int i = 0; i < list.size(); i++){
JsonElement weatherItem = list.get(i);
Integer dt = Integer.valueOf(weatherItem.getAsString("dt").toString());
}
But this part Integer dt = Integer.valueOf(weatherItem.getAsString("dt").toString())
doesnt work.
It should get values from every dt
and compate to tomorrowTime
The second part will look like this:
long diff = Math.abs(tomorrowTime - dt);
if(diff < timeDifference){
timeDifference = diff;
minDtIndex = i;
Upvotes: 1
Views: 661
Reputation: 433
Integer dt = Integer.valueOf(weatherItem.getAsString("dt").toString());
In this line, you are going to get the following compilation error:
getAsString( )
in JsonElement cannot be applied
This is because the getAsString()
doesn't not accept any parameters, this is your Syntax Error here.
Semantically you have first have interpret the JSON Element
as JSON Object
, once it's a JSON Object then you can extract your property named dt.
The way to do that is:
Integer dt = new Integer(weatherItem.getAsJsonObject().get("dt").getAsInt());
I'll reference this Question and to read about the JSON format itself on W3-Schools
The Rest you can manage on your own logic and coding :) Happy Coding!
Upvotes: 1