从json响应调用时,GSON抛出错误

时间:2015-11-13 09:35:56

标签: java android json gson

每当我尝试加载{"status":true,"statuscode":200,"message":"List(s) found!","result":[{"id":"1","name":"Afghan (AFGHANISTAN)","country_code":"AF"},{"id":"2","name":"Albanian (ALBANIA)","country_code":"AL"}],"batch":2,"totalrows":2} 命令时,它总会抛出异常。错误是

  

com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:   预期BEGIN_ARRAY但在第7行第2列路径为BEGIN_OBJECT

我发送的JSON结果是:

package com.app.testapp.test.models;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.google.gson.annotations.SerializedName;

public class TestModel extends Model {

    @Column(name="id")
    @SerializedName("id")
    String id;

    @Column(name="name")
    @SerializedName("name")
    String name;

    @Column(name="country_code")
    @SerializedName("country_code")
    String country_code;

    public String getTestModelId(){ return id;}

    public void setTestModelId(String TestModelId){
        this.id = TestModelId;
    }

    public String getTestModelName(){ return ("name")

    public void setTestModelName(String TestModelName){
        this.name = TestModelName;
    }

    public String TestModelCode(){ return country_code;}

    public void SetTestModelCode(String TestModelCode){
        this.country_code = TestModelCode;
    }

    @Override
    public String toString(){
        return "Nationality [NationalityId="+id+", NationalityName="+name+" , " +
                "NationalityCode="+country_code+"]";

    }
}

这是TestModel:

   Gson gson = new GsonBuilder().create();

    Type listType = new TypeToken<List<TestModel>>() {
    }.getType();

    try {
        Log.v("MyTag","Try");

        List<TestModel> result = gson.fromJson(new String(responseBody), listType); -- error here

        callback.onGetTestSucess(result);
    } catch (Exception e) {

        callback.onGetTestFailure();

这是在我的httpclient类中,所有似乎都运行良好,直到错误部分

Math

GSON的问题似乎是什么?是因为我没有正确地序列化吗?

2 个答案:

答案 0 :(得分:2)

您的JSON无效

{
"status": true,
"statuscode": 200,
"message": "List(s) found!",
"result": [
    {
        "id": "1",
        "name": "Afghan (AFGHANISTAN)",
        "country_code": "AF"
    },
    {
        "id": "2",
        "name": "Albanian (ALBANIA)",
        "country_code": "AL"
    }
],
"batch": 2,
"totalrows"2" //Here is your error fix it to "totalrows": 2
} 

答案 1 :(得分:0)

您的JSON代表一个对象,如下所示。 (为了清楚起见,为了清楚起见,吸气剂,制定者等等)

class ResponseModel {
    Boolean status;
    Integers statuscode;
    String message;
    List<TestModel> result;
    Integer batch;
    Integer totalrows;
}

您可以使用 -

反序列化
ResponseModel response = gson.fromJson(new String(responseBody), ResponseModel);
相关问题