Click here to Skip to main content
14,869,990 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using a API called openweathermap to call for a JSON file that appears in my broswer. I want to grab an element from that JSON file so I wrote this:

URL url = new URL(",minutely,daily&appid=(apikey)");
    URLConnection request = url.openConnection();
    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.
    JsonElement elem = rootobj.get("current");

Now as you can tell I am using GSON from Google, I've created a parser object, etc. Here's what the link gets you when you call for the API. Obviously cut out longitude and latitude along with the actual API key for privacy reasons but made sure they're in my code.

"lat": redacted,
"lon": redacted,
"timezone": "redacted",
"timezone_offset": -21600,
"current": {
    "dt": 1611308462,
    "sunrise": 1611322446,
    "sunset": 1611360051,
    "temp": 51.39,
    "feels_like": 48.61,
    "pressure": 1013,
    "humidity": 100,
    "dew_point": 51.39,
    "uvi": 0,
    "clouds": 90,
    "visibility": 3219,
    "wind_speed": 5.75,
    "wind_deg": 100,
    "weather": [
           "id": redacted,
           "main": "Clouds",
           "description": "overcast clouds",
           "icon": "04n"

I can grab lat, long, timezone, timezone offset, and I've managed to pull the "current" element and print out all of it's content like temp, dt, etc. But I just want to pull "temp" from the "current" section, not all of "currents" contents. How can I do that? Here's what the
get's you:

{"dt":1611308757,"sunrise":1611322446,"sunset":1611360051,"temp":51.39,"feels_like":48.61,"pressure":1013,"humidity":100,"dew_point":51.39,"uvi":0,"clouds":40,"visibility":6437,"wind_speed":5.75,"wind_deg":160,"weather":[{"id":redacted,"main":"Clouds","description":"scattered clouds","icon":"03n"}]}

What I have tried:

I have tried to pull it as an Array but it didn't work
Updated 22-Jan-21 2:19am

1 solution

If the parser you are using deserialises the json in a dynamic way then I doubt you can stop this behaviour. If you only want certain elements from your json then you typically create classes that have the properties you are interested in and have a json deserialiser populate those classes from the json, omitting all the things that don't interest you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900