Gson Model Annotations — How to Change the Naming of Fields with @SerializedName

In the previous Gson blog post, we've introduced the first model annotation @Expose to control which properties get (de)serialized. In this blog post we'll introduce the next annotation. If you want to learn how you can change the name mapping with @SerializedName, keep reading!

Of course, this will not be the only post in our Gson series. If you're interested in the other topics, check out our series outline:

Gson Series Overview

Model Annotation @SerializedName

Besides the @Expose from the previous blog post @SerializedName is another useful annotation. @SerializedName changes the automated matching to and from the JSON. So far, we've always assumed the Java model class and the JSON have identical naming. Unfortunately, this is not always the case. Maybe you don't have access to inherited Java model classes or you've to conform to company naming policies, in either case you can use @SerializedName to make Gson's matching still work like a charm.

Let's look at an example. Our UserSimple class is back to its original form without @Expose where everything gets mapped.

public class UserSimple {  
    String name;
    String email;
    boolean isDeveloper;
    int age;
}

However, let's assume for a minute the API implementation and with that the returned JSON has changed. Our API doesn't return name anymore, it returns fullName:

{
  "age": 26,
  "email": "norman@futurestud.io",
  "fullName": "Norman",
  "isDeveloper": true
}

No worries, we don't even need to change any of our code base, we just need to add a simple annotation to our model:

public class UserSimple {  
    @SerializedName("fullName")
    String name;
    String email;
    boolean isDeveloper;
    int age;
}

With the annotation Gson's mapping is functional again and we can enjoy the benefits of automation :)

Of course, you can use @SerializedName as a way to be compliant to your corporate naming policies but also have the correct mapping to any API. This is helpful if the naming policies are vastly different.

Outlook

In this blog post, you've learned how you can utilize @SerializedName to customize the name mapping. We'll come back to the same topic of property and mapping naming in the next blog post. We'll look at a more general policy configuration. Stay tuned!

If you've feedback or a question, let us know in the comments or on twitter @futurestud_io.

Make it rock & enjoy coding!

Explore the Library

Find interesting tutorials and solutions for your problems.