Java JsonSerialize-class And Method Code Example


Here is an example of how to use the JsonSerialize annotation to serialize a Java object to JSON using the Jackson library:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class Example {
    public static void main(String[] args) throws IOException {
        Person person = new Person("John", 30);
        
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(person);
        
        System.out.println(json);
    }

    public static class Person {
        private String name;
        private int age;

        @JsonSerialize(using = CustomDateSerializer.class)
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge(){
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
}

Here is an example of using the JsonSerialize class from the com.fasterxml.jackson.databind package in Java to customize the serialization of a class:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class Example {

    @JsonSerialize(using = MyCustomSerializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date date;

    // other fields and methods
}

In this example, the JsonSerialize annotation is used to specify that a custom serializer class, MyCustomSerializer, should be used to serialize the date field. The JsonFormat annotation is also used to specify that the date should be serialized in the "yyyy-MM-dd" format.

Here is an example of custom serializer class :

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class MyCustomSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(value.toString());
    }
}

In this example, the MyCustomSerializer class is extending JsonSerializer and overrides the serialize method to perform custom serialization logic for the Date type. In this case, the date is simply being converted to a string using the toString() method.