首页 > 解决方案 > 使用 Moshi 解析嵌套 JSON 时出错

问题描述

收到错误

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);

标签: javaandroidjsonretrofit2moshi

解决方案


问题出在你的return jsonAdapter.fromJson(reader.nextString());. 通过这种方式,您说您想String从 JSON 中读取 a,但是由于您位于对象的开头(这就是$错误消息中的意思),因此您没有字符串,而是一个东西。


推荐阅读