How to register custom TypeAdapter or JsonDeserializer with Gson in Retrofit?

家住魔仙堡 提交于 2020-02-06 07:30:06

问题


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" }

( will be "0 rows processed" if request failed )

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(); 

NOTE: this question is meant to be canonical/Q&A one and a inspired by the diffulty for me to find this when I need this information once in a year. So if the example seems to be artificial and stupid it is just because it should be simple. Hope this helps others also


回答1:


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();

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();


来源:https://stackoverflow.com/questions/59513826/how-to-register-custom-typeadapter-or-jsondeserializer-with-gson-in-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!