首页 > 解决方案 > 如何使用 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

拜托,我需要帮助。谢谢

标签: androidjsongson

解决方案


首先 - 创建 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


推荐阅读