json通过gson解析返回null [英] json parsing through gson returning null
问题描述
我正在解析 json
来自 OpenWeathermap.org 就是这样的:
{
cod:200,
message:0.0016,
city:{
id:1164408,
name :美元:
coord:{
lon:68.857384,
lat:27.70516
},
国家:PK ,
population:0,
sys:{
population:0
}},
cnt:2,
list:[
{
dt:1394175600,
temp:{
day:26.31,
min :20,
max:30.17,
晚上:22.71,
前夕:30.17,
早晨:20
},
压力:1024.11,
湿度:59,
天气:[
{
id:801,
main: 云,
描述:少云,
图标: 02d
],
速度:0.91,
deg:121,
云:12
},
$ bdt:1394262000,
temp:{
day:25.58,
min:18.94,
max: 28.22,
夜晚:21.08,
前夕:28.22,
早晨:18.94
},
压力:1026.39,
湿度:58,
天气:[
{
id:800,
main:Clear,
description :天空晴朗,
icon:01d
}
],
速度:5.75,
deg:74,
云:0
}
]}
在这个 SO问题中,我让我的 Model.java
class for json
数据为
public class Model {
protected S tring cityId = null;
protected String cityName = null;
保护字符串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;
保护字符串maxTemp = null;
保护字符串minTemp = null;
保护字符串nightTimeTemp = null;
保护字符串eveTimeTemp = null;
保护字符串mornTimeTemp = null;
protected String pressure = null;
保护字符串湿度=空;
protected String windSpeed = null;
protected String WindDegree = null;
protected String clouds = null;
保护清单<天气> weathers = null;
// getters setters
public class Weather {
protected String weatherId = null;
protected String weatherCondition = null;
protected String weatherDescription = null;
保护字符串weatherIcon = null;
// getters setters
}
}}
解析专家是:
public Model getForecastByCityName(Context context,String city,int ofDays){
Model model = null;
尝试{
Gson gson = new Gson();
Reader reader = new InputStreamReader(forecastByCityName(context,city,ofDays));
model = gson.fromJson(reader,Model.class);
返回模型;
} catch(ClientProtocolException e){
e.printStackTrace();
返回null;
} catch(IOException e){
e.printStackTrace();
返回null;
$ / code $ / pre
$ b 和 forecastByCityName() / code>是:
pre $ private $ InputStream forecastByCityName
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;
}
}
我的请求已成功,但是当我尝试获取模型
对象的值:
$ p $ textView.setText(model.getCityName ()+ model.getCountryName());
打印 null null null
,为什么未能获得值?任何想法..
- Model类中的所有字段名称必须相同json keys:for国家 - 受保护的字符串国家;
- 城市json键具有自己的内部数据,因此您需要创建具有适当字段名称的City类并定义'protected City city'字段在您的Model类中。
您需要的全部内容(100%适用于您的json示例):
public class Model实现Serializable {
私有字符串cod;
私人双重信息;
私人城市城市;
私人整数cnt;
私人列表< 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实现Serializable {
private Integer id;
私人字符串名称;
@SerializedName(coord)
私人坐标坐标;
私人字符串国家;
私人整数人口;
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;
}
公共坐标getCoordinates(){
返回坐标;
}
public void setCoordinates(坐标坐标){
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实现Serializable {
@SerializedName(lon)
private double经度;
@SerializedName(lat)
私人双纬度;
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;
}
}
私人类Sys实现Serializable {
私有Integer人口;
public Integer getPopulation(){
return population;
}
public void setPopulation(Integer population){
this.population = population;
$ b private class ListItem实现Serializable {
@SerializedName(dt)
private long dateTime;
@SerializedName(temp)
private温度温度;
私人双重压力;
私人整数湿度;
私人列表<天气> weather = new ArrayList< Weather>();
私人双倍速度;
@SerializedName(deg)
私人整数程度;
私人整数云;
public Long getDateTime(){
return dateTime;
}
public void setDateTime(Long dateTime){
this.dateTime = dateTime;
}
public温度getTemperature(){
return temperature;
}
public void setTemperature(温度温度){
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;
}
公共列表< 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实现Serializable {
private double day;
私人双人分钟;
私人双人最大;
私人双晚;
@SerializedName(eve)
私人双人晚上;
@SerializedName(morn)$ b $ b私人双早;
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;
私有字符串描述;
私人字符串图标;
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;
}
}
}
}
I'm parsing json
data from OpenWeathermap.org which is like this :
{
"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
}
]}
after looking at thisSO Question, I made my Model.java
class for above json
data as
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
}
}}
parsing profess is :
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;
}
}
and forecastByCityName()
is :
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;
}
}
my request is successful, but when I try to get values from Model
object like :
textView.setText(model.getCityName() + model.getCountryName());
that prints null null null
, why that fails to get values? any idea..
- All field names in Model class must be equal json keys: for "country" - protected String country;
- "city" json key has its own inner data, so you need to create City class with appropriate field names and to define 'protected City city;' field in your Model class.
Here all you need (100 % works on your json-example):
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;
}
}
}
}
这篇关于json通过gson解析返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!