使用Moshi解析嵌套JSON时出错

时间:2018-07-18 02:34:04

标签: java android json retrofit2 moshi

收到错误

  

com.squareup.moshi.JsonDataException:预期为字符串,但在路径$

处为BEGIN_OBJECT

正在解析的JSON

被缩短以使其更易于阅读

{
    "success": true,
    "error": null,
    "data": {
        "review_on_me": [
            {
                "request_id": "51",
                "review_from": "9",
                "reviewer": {
                    "id": 9,
                    "first_name": "abc",
                    "device_meta": {
                        "device_type": "iphone",
                        "device_id": "abc"
                    },
                    "location": {
                        "latitude": "43.881731",
                        "longitude": "-79.444322"
                    }
                }
            }
    ]
}

模型类

public class ResponseGetReviews
 {
    @Json(name = "success")
    private Boolean success;
    @Json(name = "error")
    private String error;
    @Json(name = "data")
    private ReviewDataModel data;
}

正在使用JSON适配器

所有后续数据对象中的几个。这是为了展示他们的样子

public class ResponseGetReviewsAdapter extends JsonAdapter<ResponseGetReviews>
{
    @Override
    public ResponseGetReviews fromJson(JsonReader reader) throws IOException
    {
        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<ResponseGetReviews> jsonAdapter = moshi.adapter(ResponseGetReviews.class);

        return jsonAdapter.fromJson(reader.nextString());
    }

    @Override
    public void toJson(JsonWriter writer, ResponseGetReviews value) throws IOException
    {
        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<ResponseGetReviews> jsonAdapter = moshi.adapter(ResponseGetReviews.class);

        writer.value(jsonAdapter.toJson(value));
    }
}

函数调用

Moshi moshi = new Moshi.Builder()
                .add(ResponseGetReviews.class, new ResponseGetReviewsAdapter())
                .add(ReviewDataModel.class, new ReviewDataModelAdapter())
                .add(ReviewDetailModel.class, new ReviewDetailModelAdapter())
                .add(UserModel.class, new UserModelAdapter())
                .add(LocationModel.class, new LocationModelAdapter())
                .add(DeviceMetaModel.class, new DeviceMetaModelAdapter())
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RestAPI.ENDPOINT)
                .addConverterFactory(MoshiConverterFactory.create(moshi))
                .build();
        RestAPI restApi = retrofit.create(RestAPI.class);
        Call<ResponseGetReviews> getReviewsCall = restApi.getClientReviews(auth, clientId);

1 个答案:

答案 0 :(得分:0)

问题出在您的return jsonAdapter.fromJson(reader.nextString());中。这样,您就说您想从JSON中读取String,但是由于您位于对象的开头(这就是错误消息中的$的含义),您没有字符串,而是一个对象。