简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM