我从Web服务获取JSon数据,示例数据如下:
[
{
"SectionId": 1,"SectionName": "Android"
}
]
当我尝试转换它时,它会抛出一个错误,我这样做:
Data data = new Gson().fromJson(jsonDataFromWebService,Data.class);
我的科级是:
class Section
{
public int SectionId;
public String SectionName;
}
class Data {
public List<Section> sections;
}
LogCat说:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
解决方法
错误解释了什么错误…你返回一个数组而不是一个JSon对象
尝试如下:
JSONArray ja = new JSONArray(jsonStringReturnedByService);
Data sections = new Data();
for (int i = 0; i < ja.length(); i++) {
Section s = new Section();
JSONObject jsonSection = ja.getJSONObject(i);
s.SectionId = Integer.ValueOf(jsonSection.getString("SectionId"));
s.SectionName = jsonSection.getString("SectionName");
//add it to sections list
sections.add(s);
}
return sections;