Custom Field-Level Serialization in Jackson JSON: Implementing int to string Conversion

Dec 04, 2025 · Programming · 10 views · 7.8

Keywords: Jackson JSON | Custom Serialization | Field Control

Abstract: This article delves into custom field-level serialization using the Jackson JSON processor. Through a case study—serializing the favoriteNumber field in a Person class from int to a JSON string instead of the default number type—it details two solutions: custom JsonSerializer and built-in ToStringSerializer. Starting from core concepts, the article step-by-step explains annotation configuration, serializer implementation principles, and best practices, helping developers master key techniques for flexible JSON output control.

Introduction and Problem Context

In modern Java applications, JSON serialization is a core aspect of data exchange. Jackson, as a widely-used JSON processor, defaults to mapping Java primitive types like int to JSON number types. However, real-world business scenarios often require finer control, such as serializing numeric fields as strings to meet specific API formats or compatibility needs. This article uses the Person class as an example to explore how to implement custom field-level serialization.

Core Solution: Custom JsonSerializer

Based on the best answer, custom serialization logic can be achieved by implementing the JsonSerializer interface and using the @JsonSerialize annotation. First, define the Person class:

public class Person {
    public String name;
    public int age;
    @JsonSerialize(using = IntToStringSerializer.class, as = String.class)
    public int favoriteNumber;
}

Here, the @JsonSerialize annotation specifies the custom serializer IntToStringSerializer and indicates the target type as string via as = String.class. Next, implement the serializer:

import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.core.JsonGenerator;
import java.io.IOException;

public class IntToStringSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeObject(value.toString());
    }
}

This serializer converts the Integer value to a string and writes it to the JSON generator. Jackson automatically handles boxing from int to Integer, ensuring type compatibility. Run the example:

Person person = new Person();
person.name = "Joe";
person.age = 25;
person.favoriteNumber = 123;
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(person);
System.out.println(json); // Output: {"name":"Joe","age":25,"favoriteNumber":"123"}

In the output, age is the number 25, while favoriteNumber is the string "123", achieving precise control.

Supplementary Solution: Using Built-in ToStringSerializer

As a reference, Jackson provides a built-in ToStringSerializer to simplify implementation. Modify the Person class:

public class Person {
    public String name;
    public int age;
    @JsonSerialize(using = ToStringSerializer.class)
    public int favoriteNumber;
}

ToStringSerializer is a standard serializer in the com.fasterxml.jackson.databind.ser.std package that directly converts objects to their string representation. Its internal implementation is similar to a custom serializer but more general, suitable for various types. This method reduces code volume, but custom serializers offer greater flexibility in complex logic.

In-depth Analysis and Best Practices

The core of custom serialization lies in understanding Jackson's serialization flow. When an ObjectMapper serializes an object, it checks field annotations and prioritizes the specified serializer. In IntToStringSerializer, the writeObject method call ensures string output, avoiding potential type errors from default number or string writes.

Best practices suggest: for simple conversions, prefer built-in serializers to improve maintainability; for complex business logic, custom serializers provide finer control. Also, consider performance impacts—custom serialization may add overhead, but it is negligible in most applications.

Conclusion

Through Jackson's custom serialization mechanism, developers can flexibly control JSON output formats to meet diverse requirements. This article starts from a case study, detailing implementation methods and comparing custom and built-in serializers. Mastering these techniques enhances the precision and adaptability of JSON processing.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.