Парсинг json при помощи gson

161
15 мая 2019, 19:50

Есть вот такой json

        {  
   "query":{  
      "count":1,
      "created":"2018-11-26T11:33:00Z",
      "lang":"ru-RU",
      "results":{  
         "channel":{  
            "units":{  
               "distance":"mi",
               "pressure":"in",
               "speed":"mph",
               "temperature":"F"
            },
            "title":"Yahoo! Weather - Homyel', Homyel'skaya Voblasts', BY",
            "link":"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-825978/",
            "description":"Yahoo! Weather for Homyel', Homyel'skaya Voblasts', BY",
            "language":"en-us",
            "lastBuildDate":"Mon, 26 Nov 2018 02:33 PM MSK",
            "ttl":"60",
            "location":{  
               "city":"Homyel'",
               "country":"Belarus",
               "region":" Homyel'skaya Voblasts'"
            },
            "wind":{  
               "chill":"23",
               "direction":"35",
               "speed":"8"
            },
            "atmosphere":{  
               "humidity":"87",
               "pressure":"997.0",
               "rising":"0",
               "visibility":"16.1"
            },
            "astronomy":{  
               "sunrise":"8:37 am",
               "sunset":"4:50 pm"
            },
            "image":{  
               "title":"Yahoo! Weather",
               "width":"142",
               "height":"18",
               "link":"http://weather.yahoo.com",
               "url":"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
            },
            "item":{  
               "title":"Conditions for Homyel', Homyel'skaya Voblasts', BY at 01:00 PM MSK",
               "lat":"52.441669",
               "long":"30.98333",
               "link":"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-825978/",
               "pubDate":"Mon, 26 Nov 2018 01:00 PM MSK",
               "condition":{  
                  "code":"26",
                  "date":"Mon, 26 Nov 2018 01:00 PM MSK",
                  "temp":"29",
                  "text":"Cloudy"
               },
               "forecast":[  
                  {  
                     "code":"28",
                     "date":"26 Nov 2018",
                     "day":"Mon",
                     "high":"30",
                     "low":"16",
                     "text":"Mostly Cloudy"
                  },
                  {  
                     "code":"28",
                     "date":"27 Nov 2018",
                     "day":"Tue",
                     "high":"25",
                     "low":"17",
                     "text":"Mostly Cloudy"
                  },
                  {  
                     "code":"28",
                     "date":"28 Nov 2018",
                     "day":"Wed",
                     "high":"24",
                     "low":"15",
                     "text":"Mostly Cloudy"
                  },
                  {  
                     "code":"32",
                     "date":"29 Nov 2018",
                     "day":"Thu",
                     "high":"16",
                     "low":"6",
                     "text":"Sunny"
                  },
                  {  
                     "code":"32",
                     "date":"30 Nov 2018",
                     "day":"Fri",
                     "high":"18",
                     "low":"8",
                     "text":"Sunny"
                  },
                  {  
                     "code":"28",
                     "date":"01 Dec 2018",
                     "day":"Sat",
                     "high":"19",
                     "low":"10",
                     "text":"Mostly Cloudy"
                  },
                  {  
                     "code":"28",
                     "date":"02 Dec 2018",
                     "day":"Sun",
                     "high":"21",
                     "low":"18",
                     "text":"Mostly Cloudy"
                  },
                  {  
                     "code":"28",
                     "date":"03 Dec 2018",
                     "day":"Mon",
                     "high":"29",
                     "low":"19",
                     "text":"Mostly Cloudy"
                  },
                  {  
                     "code":"28",
                     "date":"04 Dec 2018",
                     "day":"Tue",
                     "high":"28",
                     "low":"24",
                     "text":"Mostly Cloudy"
                  },
                  {  
                     "code":"26",
                     "date":"05 Dec 2018",
                     "day":"Wed",
                     "high":"31",
                     "low":"26",
                     "text":"Cloudy"
                  }
               ],
               "description":"<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/26.gif\"/>\n<BR />\n<b>Current Conditions:</b>\n<BR />Cloudy\n<BR />\n<BR />\n<b>Forecast:</b>\n<BR /> Mon - Mostly Cloudy. High: 30Low: 16\n<BR /> Tue - Mostly Cloudy. High: 25Low: 17\n<BR /> Wed - Mostly Cloudy. High: 24Low: 15\n<BR /> Thu - Sunny. High: 16Low: 6\n<BR /> Fri - Sunny. High: 18Low: 8\n<BR />\n<BR />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-825978/\">Full Forecast at Yahoo! Weather</a>\n<BR />\n<BR />\n<BR />\n]]>",
               "guid":{  
                  "isPermaLink":"false"
               }
            }
         }
      }
   }
}

Надо вывести в формате
день;минимальная температура в цельсиях;максимальная температура;погода

Нужно использовать библиотеку gson. Нашел как сделать вот это

public class Forecast {
@SerializedName("code")
@Expose
private String code;
@SerializedName("date")
@Expose
private String date;
@SerializedName("day")
@Expose
private String day;
@SerializedName("high")
@Expose
private String high;
@SerializedName("low")
@Expose
private String low;
@SerializedName("text")
@Expose
private String text;

public Forecast() {
}
/**
* 
* @param text
* @param high
* @param day
* @param code
* @param low
* @param date
*/
public Forecast(String code, String date, String day, String high, String low, String text) {
super();
this.code = code;
this.date = date;
this.day = day;
this.high = high;
this.low = low;
this.text = text;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getHigh() {
return high;
}
public void setHigh(String high) {
this.high = high;
}
public String getLow() {
return low;
}
public void setLow(String low) {
this.low = low;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

Искал много информации в интернете, но по аналогии сделать не получилось, в том ли я вообще направлении пытаюсь сделать что-то?

Answer 1

Можно как то вот так:

    JSONObject json = new JSONObject(jsonString);
    JSONArray forecastJson = json.optJSONObject("query")
            .optJSONObject("results")
            .optJSONObject("channel")
            .optJSONObject("item")
            .optJSONArray("forecast");
    Gson gson = new Gson();
    Type type = new TypeToken<ArrayList<Forecast>>(){}.getType();
    List<Forecast> forecast = gson.fromJson(forecastJson.toString(), type);
READ ALSO
Ошибка [INSTALL_CANCELED_BY_USER] на устройстве XiaomiNote5

Ошибка [INSTALL_CANCELED_BY_USER] на устройстве XiaomiNote5

В моем случае я нажал Запретить, во время первой установкиПоэтому я получил INSTALL_FAILED_USER_RESTRICTED

130
С чем связана ошибка (лог из PlayMarket ниже)

С чем связана ошибка (лог из PlayMarket ниже)

Ошибка возникла на устройстве Lenovo VIBE K10 (K10a40), Android 60

142
скрытие и открытие окна javaFX

скрытие и открытие окна javaFX

Я реализовываю простое переключение окон, нажал Button1 (на Windows1) - открылось Windiws2, где есть Button2, нажал там уже Button2 - вернулось Windows1Из примеров...

153