java - 使用 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);
解决方案
问题出在你的return jsonAdapter.fromJson(reader.nextString());
. 通过这种方式,您说您想String
从 JSON 中读取 a,但是由于您位于对象的开头(这就是$
错误消息中的意思),因此您没有字符串,而是一个东西。
推荐阅读
- python - Python确定屏幕阅读器已启用
- django - 我想将 django QUERY 表示为 html 页面中的表格,表格标题与 django 字段名称相同。我该如何实施?
- reactjs - React 路由器 - 如何路由到具有特定帖子 ID 的页面
- mysql - 创建一个存储过程,可以在表中添加、删除和更新记录,用户可以在其中选择他想要的操作
- mysql - mid((user)from(-1)) 在mysql中的含义。from(-1) 是什么意思?
- python - 如何使用 python 比较两个不同的 csv 文件?
- docker - 如何将一个容器的输出文件夹映射到另一个容器的挂载文件夹?
- python - Python如何在不导入的情况下调用类方法
- apache-iotdb - Apache IoTDB 版本 0.12.1 中的“喜欢”sql 语法错误
- google-sheets - 如何根据不同的列合并行(可以查询吗?)