android - 如何使用 GSON 实现 json?得到一个错误
问题描述
我存储在字符串中的 json 的结构是:
{
"0": {
"PDate": "2019-02-25 00:00:00.0000000",
"DDate": "2019-06-25 00:00:00.0000000",
"Document": "FC",
"Direction": "CALLE ...."
},
"1": {
"PDate": "2019-02-25 00:00:00.0000000",
"DDate": "2019-06-25 00:00:00.0000000",
"Document": "FC",
"Direction": "CALLE ...."
}
}
我正在使用以下代码,但它在最后一行显示错误:
if (response.isSuccessful()){
Object object = response.body();
String jsonString = String.valueOf(object);
Gson gson = new Gson();
Type empMapType = new TypeToken<Map<Integer, Object>>() {}.getType();
Map<Integer, Object> nameObjectJson = gson.fromJson(jsonString, empMapType);
}
错误信息:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 29 path $..PostingDate
拜托,我需要帮助。谢谢
解决方案
首先 - 创建 POJO / Model 类来转换您的响应。
public class SomeModel{
@SerializedName("name")
@Expose
private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
宣布你的回应
Gson gson = new Gson();
SomeModelResponse response = gson.toJson(result, SomeModel.class);
如果您将多次使用 Gson 对象 - 最好创建它的单例,因为每次创建它的新实例时 - 它都会使用大量内存。
添加检查后:
if(response !=null && response.getName() !=null){
if(response.getName().equalIgnoreCase("some name")){
// show toast Result Success !!! and move to next screen
}
else if(response.getName().equalIgnoreCase("another name")){
// Invalid Response !!! your logic here
}
}
另外不要忘记检查您期望得到什么样的响应。它不应该是 Object.class
推荐阅读
- paypal - 如何使用 PayPal 订阅多个定期付款计划?
- python - 使用 for 循环与使用 .copy() 或 [:] 复制列表
- c++ - 删除的功能,不能将一条记录重写为另一条记录,对象
- xamarin.forms - 无法在 UWP 应用程序中发现蓝牙设备,但在 WPF 应用程序中工作
- react-native - 如何在 React Native 中的身份验证状态更改时更改路由
- python - PyCharm IDE:“import @”代码有效,但“from @import @”无效
- javascript - 使用 Jest 模拟节点模块时出现 TypeError
- mysql - 约束一个值在 mySQL 的同一列中最多重复 3 次
- laravel - 下载页面的视图和控制器
- r - 计算大于 0 的值并计算有多少与一行中的模式匹配(在 R 中)