繁体   English   中英

使用GSON从JSON获取数组及其对象

[英]Get Array and it's objects from JSON using GSON

我有这个字符串:

{"cod":"200","message":0.0049,"cnt":40,"list":[{"dt":1549346400,"main":{"temp":-1.04,"temp_min":-1.04,"temp_max":-1.04,"pressure":1023.46,"sea_level":1025.98,"grnd_level":1023.46,"humidity":92,"temp_kf":0},"weather":[{"id":600,"main":"Snow","description":"небольшой снегопад","icon":"13n"}],"clouds":{"all":80},"wind":{"speed":3.26,"deg":226.502},"rain":{},"snow":{"3h":1.485},"sys":{"pod":"n"},"dt_txt":"2019-02-05 06:00:00"},{"dt":1549357200,"main":{"temp":-1.04,"temp_min":-1.04,"temp_max":-1.04,"pressure":1023.78,"sea_level":1026.44,"grnd_level":1023.78,"humidity":95,"temp_kf":0},"weather":[{"id":600,"main":"Snow","description":"небольшой снегопад","icon":"13d"}],"clouds":{"all":80},"wind":{"speed":5.32,"deg":243.5},"rain":{},"snow":{"3h":1.115},"sys":{"pod":"d"},"dt_txt":"2019-02-05 09:00:00"}],"city":{"id":536203,"name":"Sankt-Peterburg","coord":{"lat":59.9167,"lon":30.25},"country":"RU"}}

这是一个JSON,我做了这个类来获取数据

public class FiveDaysWeather {

    private long dt;
    private List<WeatherTomorrow> weather = null;
    private Temp main;
    private Wind wind;

    public long getDt() {
        return dt;
    }

    public void setDt(long dt) {
        this.dt = dt;
    }

    public List<WeatherTomorrow> getWeatherTomorrow() {
        return weather;
    }

    public void setWeatherTomorrow(List<WeatherTomorrow> weather) {
        this.weather = weather;
    }

    public Temp getTemp() {
        return main;
    }

    public void setTemp(Temp main) {
        this.main = main;
    }

    public Wind getWind() {
        return wind;
    }

    public void setWind(Wind wind) {
        this.wind = wind;
    }
}

public class WeatherTomorrow {
    private String icon;
    private String description;
    private String main;
    private long id;

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getMain() {
        return main;
    }

    public void setMain(String main) {
        this.main = main;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

因此,我还需要从该字符串中获取有关天气(温度,湿度,描述和风)的数据,该数据位于第一个dt“ 1549346400”中的数组“ list”中。 我做了一个JSON数组,并把“列表”作为JSONArray。 han,我从列表“ dt 1549346400”中获取了JSONObject,并使用getter获取数据。

现在,我需要使用Google GSON做同样的事情。 阅读github上的指南,但仍然不了解如何从JSON获取0索引数据。

String jsonStr = "{}";

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM