gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:59:42 33 4
gpt4 key购买 nike

我知道这可能是不良 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com