我从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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。