Android的JSON错误"预期BEGIN_OBJECT但BEGIN_ARRAY在行1列2英寸 [英] Android JSon error "Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2"

查看:125
本文介绍了Android的JSON错误"预期BEGIN_OBJECT但BEGIN_ARRAY在行1列2英寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Web服务得到JSON数据,样本数据如下:

  [
  {
    SectionId:1,
    SectionName:机器人
  }
]
 

当我尝试转换它,它抛出一个错误,我这样做的:

 数据数据=新GSON()fromJson(jsonDataFromWebService,Data.class)。
 

我的科类是:

 类科
{
    公众诠释SectionId;
    公共字符串SectionName;
}

类数据{
    公开名单<节>段;
}
 

的LogCat中说:

  

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:   预计BEGIN_OBJECT但BEGIN_ARRAY位于第1行第2列

解决方案

错误解释了什么是错...乌尔返回一个数组,而不是一个JSON对象

尝试如下:

  JSONArray JA =新JSONArray(jsonStringReturnedByService);

数据部分=新的Data();

的for(int i = 0; I< ja.length();我++){
    部分S =新科();
    的JSONObject jsonSection = ja.getJSONObject(ⅰ);

    s.SectionId = Integer.ValueOf(jsonSection.getString(SectionId));
    s.SectionName = jsonSection.getString(SectionName);

   //将其添加到部分名单
   sections.add(多个);
}

返回段;
 

I am getting JSon data from a web service, the sample data is given below:

[
  {
    "SectionId": 1,
    "SectionName": "Android"
  }
]

When i try to convert it, it throws an error, i am doing it as:

Data data = new Gson().fromJson(jsonDataFromWebService, Data.class);

My Section Class is:

class Section
{
    public int SectionId;
    public String SectionName;
}

class Data {
    public List<Section> sections;
}

The LogCat says:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

解决方案

The error explains whats wrong... u r returning an array and not a JSon object

try as following:

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;

这篇关于Android的JSON错误&QUOT;预期BEGIN_OBJECT但BEGIN_ARRAY在行1列2英寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆