Usage of gson library

Ahmet Kucuk
May 17, 2015 · 2 min read

I have been using google-gson library for a long time. In one of the recent projects, however, I discovered more advanced features of gson library and decided to share them on this post.

I want to start with most basic features of gson. This User class is used in all examples below.

public class User {
private String username;
private String email;
private String password;
//private transient String password;
public User(String u, String e, String p) {this.username = u; = e;this.password = p;}
public String toString() {
return "User{" +
"username='" + username + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +

Serialising and deserialising User class is as easy as follows;

User user = new User("ahmetkucuk", "", "123456");
Gson gson = new GsonBuilder().create();

System.out.println("User before serrialize: " + user.toString());
String jsonString = gson.toJson(user);
System.out.println("User serrialized json: " + jsonString);
User userFromJson = gson.fromJson(jsonString, User.class);
System.out.println("User deserrialize: " + user.toString());

What if you want to serialise your object using custom serialiser. Gson has great solution for this.

Simply define your custom serialiser and register it to gson object.

public static class UserSerializer implements JsonSerializer<User> {
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
obj.addProperty("name", src.getUsername());
obj.addProperty("email", src.getEmail());
return obj;
Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserSerializer()).create();

What if you don’t want to define custom serialise but you just want to expose specific fields. Then, there is easy solution.

Add expose annotation to fields that you want to expose( than create you gson object accordingly. Only the fields with expose annotations will be serialised.

Gson gson2 = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
jsonString = gson2.toJson(user);
System.out.println("User deserrialize: " + jsonString);

There is also a way to exclude specific fields.

Gson gson3 = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
jsonString = gson3.toJson(user);
System.out.println("User deserrialize: " + jsonString);

Finally, you can also define your own exclusion strategy. Define your own annotation interface as follow:

public @interface Exclude {

Then, add this annotation to the fields that you don’t want to serialise. Define and register your own exclusion strategy.

* From a stackoverflow post:
public class AnnotationExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Exclude.class) != null;
public boolean shouldSkipClass(Class<?> clazz) {
return false;
Gson gson = new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();

As a result, gson is easily configurable and extendible towards your needs.

Sample code is available on Github:

Ahmet Kucuk

Ahmet’s Personal Blog

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store