使用Retrofit如何在没有对象解析的情况下解析JSONArray?

时间:2017-02-13 10:31:22

标签: android json gson retrofit2

我正在解析以下Json格式:

{
msg: "success",
status_code: 200,
data: [
{
....
}  ]
}

我在后面的对象中使用Retorfit2解析它:

public class Model {
    @SerializedName("status_code")
    int statusCode;
    @SerializedName("msg")
    private String statusMsg;
    @SerializedName("data")
    private JSONArray data;

}

我想将'data'解析为JSONArray而不是特定的Model类型,而不管它的内部对象结构如何。但它给出了以下例外,问题是什么?

  W/System.err: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 44 path $.data
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
W/System.err:     at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117)
W/System.err:     at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
W/System.err:     at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106)
W/System.err:     at okhttp3.RealCall$AsyncCall.execute(RealCall.java:133)
W/System.err:     at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err:     at java.lang.Thread.run(Thread.java:761)
W/System.err: Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 44 path $.data
W/System.err:     at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
W/System.err:   ... 12 more

1 个答案:

答案 0 :(得分:1)

查看以下代码行。

`

public class Model {
    @SerializedName("status_code")
    int statusCode;
    @SerializedName("msg")
    private String statusMsg;
    @SerializedName("data")
    private **ArrayList<JSONObject>** data;

}

`