首页 > 解决方案 > 使用 GSON 从 JSON 获取数组及其对象

问题描述

我有这个字符串:

{"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”的数组“列表”中。我做了一个 JSON 数组并将“列表”作为 JSONArray。Yhan 我从这个列表中得到“dt 1549346400”作为 JSONObject 并使用 getter 来获取数据。

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

标签: javagson

解决方案


String jsonStr = "{}";

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

推荐阅读