Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Trying to use GSON on weather json

Hi all,

Can someone please explain how to structure my forecast class for GSON parsing?

The weather data we are interested is inside the Data array which is inside the larger Hourly object:

{
  "latitude": 47.20296790272209,
  "longitude": -123.41670367098749,
  "timezone": "America/Los_Angeles",

"hourly": {
    "summary": "Rain throughout the day.",
    "icon": "rain",
    "data": [
      {
        "time": 1453399200,
        "summary": "Rain",
        "icon": "rain",
        "precipIntensity": 0.1379,
        "precipProbability": 0.85,
        "precipType": "rain",
        "temperature": 48.16,
        "apparentTemperature": 46.41,
        "dewPoint": 46.89,
        "humidity": 0.95,
        "windSpeed": 4.47,
        "windBearing": 166,
        "visibility": 3.56,
        "cloudCover": 0.39,
        "pressure": 1009.97,
        "ozone": 328.71
      },
     .
     .
     .
}
}

The examples I find online do not demonstrate how to parse this scenario.

For anyone wondering, using GSON was a suggestion in teacher's notes in the following Android track video: https://teamtreehouse.com/library/android-lists-and-adapters/updating-the-data-model/from-jsonarray-to-a-java-array

1 Answer

You're most of the way there honestly. Since Gson deserializes JSON objects onto Java classes, every time you see a new object inside the JSON you need a Java class to represent it. Here was my solution:

public class Forcast {
    Double latitude;
    Double longitude;
    String timezone;
    Hourly hourly;
}

public class Hourly {
    String summary;
    String icon;
    ArrayList<Data> data;
}

public class Data {
    Long time;
    String summary;
    String icon;
    Double precipIntensity;
    Double precipProbability;
    String precipType;
    Double temperature;
    Double apparentTemperature;
    Double dewPoint;
    Double humidity;
    Double windSpeed;
    Double windBearing;
    Double visibility;
    Double cloudCover;
    Double pressure;
    Double ozone;
}

With all of the JSON objects mapped to corresponding Java classes, you can then do something like this:

Gson gson = new Gson();
Forcast forcast = gson.fromJson(json, Forcast.class);

You can then access the individual fields with something like this:

forcast.hourly.data.get(0).summary

Hope that helps!