json解析通过gson返回null

时间:2014-03-07 07:59:00

标签: android json gson

我正在解析来自OpenWeathermap.orgjson数据,如下所示:

{
   "cod":"200",
"message":0.0016,
"city":{
  "id":1164408,
  "name":"Sukkur",
  "coord":{
     "lon":68.857384,
     "lat":27.70516
  },
  "country":"PK",
  "population":0,
  "sys":{
     "population":0
  }  },  

"cnt":2,
"list":[
  {
     "dt":1394175600,
     "temp":{
        "day":26.31,
        "min":20,
        "max":30.17,
        "night":22.71,
        "eve":30.17,
        "morn":20
     },
     "pressure":1024.11,
     "humidity":59,
     "weather":[
        {
           "id":801,
           "main":"Clouds",
           "description":"few clouds",
           "icon":"02d"
        }
     ],
     "speed":0.91,
     "deg":121,
     "clouds":12
  },
  {
     "dt":1394262000,
     "temp":{
        "day":25.58,
        "min":18.94,
        "max":28.22,
        "night":21.08,
        "eve":28.22,
        "morn":18.94
     },
     "pressure":1026.39,
     "humidity":58,
     "weather":[
        {
           "id":800,
           "main":"Clear",
           "description":"sky is clear",
           "icon":"01d"
        }
     ],
     "speed":5.75,
     "deg":74,
     "clouds":0
  }
]}

查看此SO Question后,我将Model.java课程作为上述json数据的

public class Model{

protected String cityId = null;
protected String cityName = null;
protected String countryName = null;
protected String longitude = null;
protected String latitude = null;
protected String polution = null;
protected List<ForecatList> forcastList = null;
// getters setters
public class ForecatList {
    protected String dayTimeTemp = null;
    protected String maxTemp = null;
    protected String minTemp = null;
    protected String nightTimeTemp = null;
    protected String eveTimeTemp = null;
    protected String mornTimeTemp = null;
    protected String pressure = null;
    protected String humidity = null;
    protected String windSpeed = null;
    protected String WindDegree = null;
    protected String clouds = null;
    protected List<Weather> weathers = null;
    // getters setters
    public class Weather {
        protected String weatherId = null;
        protected String weatherCondition = null;
        protected String weatherDescription = null;
        protected String weatherIcon = null;
        // getters setters
    }
}}

解析信托是:

public Model getForecastByCityName(Context context, String city, int ofDays){
    Model model = null;     
    try {           
        Gson gson = new Gson();
        Reader reader = new InputStreamReader(forecastByCityName(context, city, ofDays));           
        model = gson.fromJson(reader, Model.class);         
        return model;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }   
}

forecastByCityName()是:

private InputStream forecastByCityName(Context context, String city, int ofDays) throws ClientProtocolException, IOException{
    HttpClient httpClient = null;
    StringBuilder url = new StringBuilder(URL_FORCAST);
    url.append(city);
    url.append(String.valueOf(ofDays));
    url.append(UNIT);
    HttpGet httpRequest = new HttpGet(url.toString());
    httpClient = new DefaultHttpClient();
    HttpResponse httpResponse = httpClient.execute(httpRequest);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        HttpEntity httpEntity = httpResponse.getEntity();
        return httpEntity.getContent();
    }else {
        return null;            
    }       
}

我的请求是成功的,但是当我尝试从Model对象获取值时:

textView.setText(model.getCityName() + model.getCountryName());                             

打印null null null,为什么无法获取值?任何想法..

3 个答案:

答案 0 :(得分:5)

  1. Model类中的所有字段名称必须等于json keys:for“country” - protected String country;
  2. “city”json key有自己的内部数据,因此您需要创建具有适当字段名称的City类并定义“受保护的城市城市”; Model类中的字段。
  3. 这里所有你需要的(100%适用于你的json示例):

    public class Model implements Serializable {
    
    private String cod;
    private Double message;
    private City city;
    private Integer cnt;
    private List<ListItem> list = new ArrayList<ListItem>();
    
    public String getCod() {
        return cod;
    }
    
    public void setCod(String cod) {
        this.cod = cod;
    }
    
    public Double getMessage() {
        return message;
    }
    
    public void setMessage(Double message) {
        this.message = message;
    }
    
    public City getCity() {
        return city;
    }
    
    public void setCity(City city) {
        this.city = city;
    }
    
    public Integer getCnt() {
        return cnt;
    }
    
    public void setCnt(Integer cnt) {
        this.cnt = cnt;
    }
    
    public List<ListItem> getList() {
        return list;
    }
    
    public void setList(List<ListItem> list) {
        this.list = list;
    }
    
    private class City implements Serializable { 
        private Integer id;
        private String name;
        @SerializedName("coord")
        private Coordinates coordinates;
        private String country;
        private Integer population;
        private Sys sys;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Coordinates getCoordinates() {
            return coordinates;
        }
    
        public void setCoordinates(Coordinates coordinates) {
            this.coordinates = coordinates;
        }
    
        public String getCountry() {
            return country;
        }
    
        public void setCountry(String country) {
            this.country = country;
        }
    
        public Integer getPopulation() {
            return population;
        }
    
        public void setPopulation(Integer population) {
            this.population = population;
        }
    
        public Sys getSys() {
            return sys;
        }
    
        public void setSys(Sys sys) {
            this.sys = sys;
        }
    
        private class Coordinates implements Serializable {
            @SerializedName("lon")
            private Double longitude;
            @SerializedName("lat")
            private Double latitude;
    
            public Double getLongitude() {
                return longitude;
            }
    
            public void setLongitude(Double longitude) {
                this.longitude = longitude;
            }
    
            public Double getLatitude() {
                return latitude;
            }
    
            public void setLatitude(Double latitude) {
                this.latitude = latitude;
            }
        }
    
        private class Sys implements Serializable {
            private Integer population;
    
            public Integer getPopulation() {
                return population;
            }
    
            public void setPopulation(Integer population) {
                this.population = population;
            }
        }
    }
    
    private class ListItem implements Serializable {
        @SerializedName("dt")
        private Long dateTime;
        @SerializedName("temp")
        private Temperature temperature;
        private Double pressure;
        private Integer humidity;
        private List<Weather> weather = new ArrayList<Weather>();
        private Double speed;
        @SerializedName("deg")
        private Integer degree;
        private Integer clouds;
    
        public Long getDateTime() {
            return dateTime;
        }
    
        public void setDateTime(Long dateTime) {
            this.dateTime = dateTime;
        }
    
        public Temperature getTemperature() {
            return temperature;
        }
    
        public void setTemperature(Temperature temperature) {
            this.temperature = temperature;
        }
    
        public Double getPressure() {
            return pressure;
        }
    
        public void setPressure(Double pressure) {
            this.pressure = pressure;
        }
    
        public Integer getHumidity() {
            return humidity;
        }
    
        public void setHumidity(Integer humidity) {
            this.humidity = humidity;
        }
    
        public List<Weather> getWeather() {
            return weather;
        }
    
        public void setWeather(List<Weather> weather) {
            this.weather = weather;
        }
    
        public Double getSpeed() {
            return speed;
        }
    
        public void setSpeed(Double speed) {
            this.speed = speed;
        }
    
        public Integer getDegree() {
            return degree;
        }
    
        public void setDegree(Integer degree) {
            this.degree = degree;
        }
    
        public Integer getClouds() {
            return clouds;
        }
    
        public void setClouds(Integer clouds) {
            this.clouds = clouds;
        }
    
        private class Temperature implements Serializable {
            private Double day;
            private Double min;
            private Double max;
            private Double night;
            @SerializedName("eve")
            private Double evening;
            @SerializedName("morn")
            private Double morning;
    
            public Double getDay() {
                return day;
            }
    
            public void setDay(Double day) {
                this.day = day;
            }
    
            public Double getMin() {
                return min;
            }
    
            public void setMin(Double min) {
                this.min = min;
            }
    
            public Double getMax() {
                return max;
            }
    
            public void setMax(Double max) {
                this.max = max;
            }
    
            public Double getNight() {
                return night;
            }
    
            public void setNight(Double night) {
                this.night = night;
            }
    
            public Double getEvening() {
                return evening;
            }
    
            public void setEvening(Double evening) {
                this.evening = evening;
            }
    
            public Double getMorning() {
                return morning;
            }
    
            public void setMorning(Double morning) {
                this.morning = morning;
            }
        }
    
        private class Weather implements Serializable {
            private Integer id;
            private String main;
            private String description;
            private String icon;
    
            public Integer getId() {
                return id;
            }
    
            public void setId(Integer id) {
                this.id = id;
            }
    
            public String getMain() {
                return main;
            }
    
            public void setMain(String main) {
                this.main = main;
            }
    
            public String getDescription() {
                return description;
            }
    
            public void setDescription(String description) {
                this.description = description;
            }
    
            public String getIcon() {
                return icon;
            }
    
            public void setIcon(String icon) {
                this.icon = icon;
            }
        }
    }
    

    }

答案 1 :(得分:2)

我建议您使用某种工具自动创建模型。 我个人一直使用http://www.jsonschema2pojo.org/

答案 2 :(得分:2)

您的POJO不适合JSON输出。您需要为Gson创建城市对象以捕获城市数据。要获取城市和国家/地区名称,您需要执行以下操作;

public class Model {
    private String cod;
    private City city;

    // To catch the forecasts list
    private List<ForecastList> list;

    // Alternatively if you want the variable to be called forecastList
    // you can do the following
    @SerializedName("list")
    private List<ForecastList> forecastList;

    public class City {
        private String name;
        private String country;

        public String getName() {
            return name;
        }

        public String getCountry() {
            return country;
        }
    }

    public City getCity() {
        return city;
    }

    // Omitted for brevity
}

然后,您可以通过执行以下操作获取城市和国家/地区名称;

Gson gson = new Gson();
Reader reader = new InputStreamReader(forecastByCityName(context, city, ofDays));           
Model model = gson.fromJson(reader, Model.class);
String cityName = model.getCity().getName();
String cityCountry = model.getCity().getCountry();

或者,如果您希望在方便的时候在Model上制作一些封装方法。