Usage of gson library

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 {
@Expose
private String username;
private String email;
@Exclude
private String password;
//private transient String password;
public User(String u, String e, String p) {this.username = u;this.email = e;this.password = p;}
@Override
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", "ahmetkucuk92@gmail.com", "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(com.google.gson.annotations.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:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
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:
*
* http://stackoverflow.com/a/27986860/2616232
*/
public class AnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Exclude.class) != null;
}
@Override
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: https://github.com/ahmetkucuk/Gson-Example