java - 如何在 Gson 中反序列化具有两种可能类型( boolean 值和字符串)的字段

标签 java json gson deserialization

我知道这可能是一个糟糕的 JSON API 实践的例子,但我被迫处理这样的 JSON 响应:

{
   "error": "Username required."
}

但是当它不是错误时,error字段变成 boolean 值:

{
   "error": false
}

如何在 Gson 中以干净的方式正确处理它(最好使用最少的配置)?

注意:在 POJO 中,我有 String getErrorMessage()boolean isError()

最佳答案

如果您不编写自定义反序列化器,Gson 就无法做到这一点。 Gson Design Document包括这一段:

Navigating the Json tree or the target Type Tree while deserializing

When you are deserializing a Json string into an object of desired type, you can either navigate the tree of the input, or the type tree of the desired type. Gson uses the latter approach of navigating the type of the target object. This keeps you in tight control of instantiating only the type of objects that you are expecting (essentially validating the input against the expected "schema"). By doing this, you also ignore any extra fields that the Json input has but were not expected.

从中您可以看到,Gson 在尝试反序列化 JSON 时会查看您的对象,因此不会考虑 JSON 文档中类型的更改。

你能做的是write a your own serialiser/deserialiser并在反序列化文档之前注册它。

关于java - 如何在 Gson 中反序列化具有两种可能类型( boolean 值和字符串)的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27119177/

相关文章:

java - 使用 NIO2 API 时摆脱检查异常

java - 更新 ResultSet 中的行会生成错误 : 'Value conflicts occurs'

json - 无法读取 JSON : Unrecognized field (. ..),未标记为可忽略

php - 在 php 中获取已知键的值失败

javascript - 本地存储的 json 数组正在打印,但 json 的值在 cordova 应用程序中给出未定义

java - 使用 GSON 使用自定义比较器反序列化扩展 TreeSet 的类

java - 从路径字符串解析 Java 对象树中的字段的最有效方法是什么?

java - onSwipe 事件未在 ViewPager 内触发

json - GSON 与 Scala : Scala scala. collection.mutable.HashMap 与 java.util.HashMap

java - 为什么我会收到未经检查的作业警告?