【问题标题】:Gson parsing fails when the JSON contains string or jsonobject for a key当 JSON 包含 key 的字符串或 jsonobject 时,Gson 解析失败
【发布时间】:2017-01-12 11:08:13
【问题描述】:

在我的 Android 应用中,我收到了来自网络服务的响应。 Web 服务将响应返回为

{
  "Result": -1,
  "Message": "E-mail/Mobile number or password is wrong, make sure your Mobile Number is entered with country code.",
  "MessageType": 2,
  "ResponseData": ""
}

如果由于凭据错误而失败。

成功时返回如下

{
  "Result": -1,
  "Message": "E-mail/Mobile number or password is wrong, make sure your Mobile Number is entered with country code.",
  "MessageType": 2,
  "ResponseData": {...}
}

也就是说,对于“ResponseData”,其值为字符串或 JSONObject。

我正在使用 Gson 进行解析。

我写了解析的POJO类

    public class LoginResponse {
        @SerializedName("Result")
        @Expose
        private Integer result;
        @SerializedName("Message")
        @Expose
        private String message;
        @SerializedName("MessageType")
        @Expose
        private Integer messageType;
        @SerializedName("ResponseData")
        @Expose
        private ResponseData responseData;
 public class ResponseData {
...
}

    }

ResponseData 是 LoginResponse 的内部类。

使用 gson 解析时:

gsonObject.fromJson(decodeString(response.body().getOutput()), LoginResponse.class);

它给了我错误:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 5 column 20 path

如何处理?

注意: decodeString() 方法给出上面指定的json对象。

【问题讨论】:

  • decodeString(response.body().getOutput() 这部分的输出是什么?使用Log/Debug获取
  • 你的响应是一个 JSON 对象,你把它当作一个字符串吗?

标签: android json


【解决方案1】:

您的回复中有一个键 responseData 的多种类型,它可以是 StringResponseData,但您的班级只能接受 ResponseData

我建议返回 null 而不是空字符串,然后您可以检查 responseData == null

【讨论】:

    【解决方案2】:

    您不能在同一位置(键)返回 String 和 JSONObject:
    "响应数据": ""
    “响应数据”:{...}

    您可以在成功时将 JsonNull 用于错误和对象,或者更好地 - 定义一个新键,如果有错误将显示给您。

    【讨论】:

      猜你喜欢
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多