Serializing and deserializing attributes with names other than Json fields

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 am receiving there is a text field and I would like the value of this attribute to be filled in my attribute named descricao .

This would not normally happen since the Gson framework relates fields and attributes with equal names, meaning Gson will look in my Java class for a text attribute to enter the value of the text attribute of Json, but the My case is different.

I also question if it is possible to do the same thing when serializing an object, for example by taking the value that is in the descricao field and inserting it into a text element of Json.

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

    
asked by anonymous 11.05.2017 / 15:24

1 answer

1

It's very simple, just use an 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 because of the name difference of the text and descricao fields, which will make the descricao field become null after 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 referring field in Json, for both serialization and deserialization . In case, it would simply be this:

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 .

    
11.05.2017 / 15:25