问题
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