如何在Retrofit中向Gson注册自定义TypeAdapter或JsonDeserializer? [英] How to register custom TypeAdapter or JsonDeserializer with Gson in Retrofit?

查看:552
本文介绍了如何在Retrofit中向Gson注册自定义TypeAdapter或JsonDeserializer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Retrofit,并且需要一些自定义反序列化以及我使用的API返回的某些响应.

I am using Retrofit in my project and I need some custom deserialization with some of the responses that the API I use returns.

仅举一个例子:我收到类似

Just for an example: I receive JSON like:

{ "status": "7 rows processed" }

(如果请求失败,将为已处理0行")

,我需要反序列化为类似这样的对象:

and I need to deserialize to an object like:

@Getter
@RequiredArgsConstructor
public static class Result {
    private final boolean success;
}

我创建了自定义反序列化器:

I have created custom deserializer:

public class ResultDeserializer implements JsonDeserializer<Result> {
    @Override
    public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        return new Result( ! json.getAsJsonObject().get("status").getAsString().startsWith("0"));
    }
}

注册后,我可以测试它的工作原理:

and I am able to test it works when I register it like:

Gson gson = new GsonBuilder().registerTypeAdapter(Result.class, new ResultDeserializer()).create(); 

注意:这个问题的意思是规范/问答,这是我一年一次需要此信息时很难找到的答案.因此,如果该示例似乎是人为的和愚蠢的,那仅仅是因为它应该很简单.希望这对其他人也有帮助

推荐答案

解决方案是在构建Retrofit客户端时注册自定义的Gson.因此,在使用自定义JsonDeserializer自定义Gson之后,如下所述:

The solution is to register customized Gson when building the Retrofit client. So after customizing Gson with custom JsonDeserializer like in question:

Gson customGson = new GsonBuilder()
    .registerTypeAdapter(Result.class, new ResultDeserializer())
    .create();

需要在构建阶段借助于GsonConverterFactoryRetrofit注册此Gson实例:

it is needed to register this Gson instance with Retrofit in building phase with help of GsonConverterFactory:

Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl("http://localhost:8080/rest/")
        .addConverterFactory(GsonConverterFactory.create(customGson))
        .build();

这篇关于如何在Retrofit中向Gson注册自定义TypeAdapter或JsonDeserializer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆