我用如下方法解析一个json字符串,但是就是运行都这就闪退了,不知道什么原因。
protected void parseData(String result) {
// TODO Auto-generated method stub
Gson gson=new Gson();
NewData data=gson.fromJson(result,NewData.class);
System.out.println(data.toString());
}
这是newData类
public class NewData{
public ArrayList<kindFood> food;
public class kindFood{
public String Description;
public String PicUrl;
public String Title;
public String Url;
@Override
public String toString() {
return "kindFood [Description=" + Description + ", PicUrl=" + PicUrl + ", Title=" + Title + ", Url="
+ Url + "]";
}
}
}
这是json数据
[
{
"Description": "",
"PicUrl": "",
"Title": "鸡蛋热量(100克)",
"Url": ""
},
{
"Description": "",
"PicUrl": "",
"Title": "鸡蛋 144 大卡",
"Url": "http://i.boohee.com/mfood/view/910"
},
{
"Description": "",
"PicUrl": "",
"Title": "鸡蛋(土鸡) 138 大卡",
"Url": "http://i.boohee.com/mfood/view/913"
},
{
"Description": "",
"PicUrl": "",
"Title": "鸡蛋(煮) 151 大卡",
"Url": "http://i.boohee.com/mfood/view/1757"
},
{
"Description": "",
"PicUrl": "",
"Title": "鸡蛋白(鸡蛋清) 60 大卡",
"Url": "http://i.boohee.com/mfood/view/914"
},
{
"Description": "",
"PicUrl": "",
"Title": "鸡蛋(白皮) 138 大卡",
"Url": "http://i.boohee.com/mfood/view/911"
},
{
"Description": "",
"PicUrl": "",
"Title": "鸡蛋(红皮) 156 大卡",
"Url": "http://i.boohee.com/mfood/view/912"
}
]
试一下不要把kindFood作为内部类
你可以只保留KindFood类 里面注意有getter setter 方法 然后
Gson gson = new Gson();
List<KindFood> listFood = gson.fromJson(result,new TypeToken<List<KindFood>>(){}.getType());
使用gsonformat插件可以快速解决类似问题
public class food{
/**
* Description :
* PicUrl :
* Title : 鸡蛋热量(100克)
* Url :
*/
private String Description;
private String PicUrl;
private String Title;
private String Url;
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public String getPicUrl() {
return PicUrl;
}
public void setPicUrl(String PicUrl) {
this.PicUrl = PicUrl;
}
public String getTitle() {
return Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
public String getUrl() {
return Url;
}
public void setUrl(String Url) {
this.Url = Url;
}
}
然后在添加到arraylist
中
你这个json数组的key是food么?而且最好把get set 方法设置了
需要使用到typetoken解析即可
首先,将kindFood这个类提出来。
其次,将NewData data=gson.fromJson(result,NewData.class);
改成KindFood data=gson.fromJson(result,kindFood[].class);