Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a Gson @DeserializedName equivalent to the @SerializedName annotation?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading