How to implement a custom serializer using the Jackson library in Java?


The Jackson API provides a number of methods to work with JSON data. By using Jackson API, we can convert Java objects to JSON string and reform the object from the JSON string. We can implement a custom serializer using the StdSerializer class and need to override the serialize(T value, JsonGenerator gen, SerializerProvider provider) method, the first argument value represents value to serialize(can not be null), the second argument gen represents generator used to output resulting Json content and the third argument provider represents provider that can be used to get serializers for serializing objects value.

Syntax

public abstract void serialize(T value, JsonGenerator gen, SerializerProvider provider) throws IOException

Example

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.*;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class JacksonSerializeTest {
   public static void main(String[] args) throws Exception {
      JacksonSerializeTest test = new JacksonSerializeTest();
      test.serialize();
   }
   public void serialize() throws Exception {
      User user = new User();
      user.setFirstName("Raja");
      user.setLastName("Ramesh");
      ObjectMapper mapper = new ObjectMapper();
      SimpleModule module = new SimpleModule();
      module.addSerializer(User.class, new UserSerializer());
      mapper.registerModule(module);

      String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user); // pretty print
      System.out.println(jsonStr);
   }
}

// User class
class User implements Serializable {
   private String firstName;
   private String lastName;
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
}

// UserSerializer class
class UserSerializer extends StdSerializer<User> {
   public UserSerializer() {
      this(null);
   }
   public UserSerializer(Class<User> t) {
      super(t);
   }
   @Override
   public void serialize(User value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
      jgen.writeStartObject();
      jgen.writeStringField("firstName", value.getFirstName());
      jgen.writeStringField("lastName", value.getLastName());
      jgen.writeEndObject();
   }
}

Output

{
   "firstName" : "Raja",
   "lastName" : "Ramesh"
}
raja
Published on 10-Oct-2019 11:50:24
Advertisements