gpt4 book ai didi

android - 为动态类型实现自定义 GsonCoverterFactory/Deserializer

转载 作者:行者123 更新时间:2023-11-29 15:36:01 25 4
gpt4 key购买 nike

如何为具有动态值的类型实现自定义 GsonConverterFactor 或 JsonDeserializer?

例如:

如果 Tags 对象有内容,它看起来像这样:

"tags": [
{
"content_id": "13",
"tag_id": "3",
"created": "2018-03-26 11:09:08",
"tag_name": "FICTION"
},
{
"content_id": "13",
"tag_id": "7",
"created": "2018-03-26 11:09:08",
"tag_name": "JUVENILE FICTION"
}
]

但是,如果它为空,它将返回:

            "tags": false

基本上,如果反序列化器将其值读取为 false,我想使标签列表 null

编辑:我正在使用 Retrofit 和 GSON。

最佳答案

你可以像这样创建一个反序列化器

public class UserResponseDeserializer implements 
JsonDeserializer<ResponseWrapper> {
@Override
public ResponseWrapper deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {


if (((JsonObject) json).get("tags") instanceof JsonArray){
return new Gson().fromJson(json, ResponseArray.class);
} else {
return new Gson().fromJson(json, ResponseBoolean.class);
}

}
}

其中 ResponseArrayResponseBoolean 扩展了 ResponseWrapper,如前所述 here

关于android - 为动态类型实现自定义 GsonCoverterFactory/Deserializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50013856/

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