I’m able to set the @SerializedName to this_field so when I use the toJson() function it’ll use it properly. However when I’m trying to read it in via fromJson() function it’ll try to use thisField.
Normally I’d create a serializer like the one below; however is there something built in that will handle this or is the only way to make a custom deserializer for each class?
A class
@Data
@Builder
@AllArgsConstructor
public class A {
@SerializedName("this_field")
private Integer thisField;
}
ADeserializer class
public class ADeserializer implements JsonDeserializer<A> {
@Override
public Additional deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject obj = jsonElement.getAsJsonObject();
return A.builder()
.thisField(obj.get("this_field").isJsonNull() ? null : obj.get("this_field").getAsJsonObject)
.build();
}
}
>Solution :
According to the doc
public abstract String[] alternate Returns: the alternative names of
the field when it is deserialized
so you can use
@SerializedName(value="this_field", alternate={"thisField"})
private Integer thisField;
This would lead into this_field being used during serialization.
During deserialization it would be used this_field if it is available and if not it will use thisField if this becomes available.