Android JSon错误“预计BEGIN_OBJECT但在第1行第2列是BEGIN_ARRAY”

前端之家收集整理的这篇文章主要介绍了Android JSon错误“预计BEGIN_OBJECT但在第1行第2列是BEGIN_ARRAY”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从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;
原文链接:https://www.f2er.com/android/313982.html

猜你在找的Android相关文章