Serializing and deserializing attributes with names different from Json fields

Asked

Viewed 693 times

0

I’m having the need to serialize and deserialize an attribute that your Json reference has a different name. For example, in the Json I’m receiving there is a field text and would like the value of this attribute to be filled in my attribute called descricao.

This would not normally happen since the Gson framework relates fields and attributes with equal names, that is, Gson will search in my Java class an attribute text to enter the attribute value text from Json, but my case is different.

I also wonder if it is possible to do the same but when serializing an object, for example taking the value that is in the field descricao and inserting into an element text json.

Is all this possible? If so, how could it be done?

  • 1

    Consider adding line breaks to your question for easy reading.

  • 1

    Added line breaks, @lazyFox. Thank you for the suggestion.

1 answer

1


It’s very simple, just use a Annotation, but first let’s visualize the problem with an example:

{
    "arrayInteger": [
        1,
        2,
        3
    ],
    "boolean": true,
    "nullObject": null,
    "number": 123,
    "text": "Hello World"
}

Note that it is not compatible with the object below due to the field name difference text and descricao, what will make the field descricao stick around null after the deserialization:

public class Objeto {
    private int[] array;
    private Boolean boolean;
    private Object nullObject;
    private String descricao;
}

To solve this, there is an annotation called @Serialize(“NOME_DO_CAMPO”), where we pass the name of the referent field in Json, both for serialization and for deserialization. In this case, it would simply be:

public class Objeto {
    private int[] array;
    private Boolean boolean;
    private Object nullObject;
    @Serialize("text")
    private String descricao;
}

After adding this notation, both serializations and deserializations will be linking text to descricao.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.