Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JSON custom serialization for certain fields

Is there a way using Jackson JSON Processor to do custom field level serialization? For example, I'd like to have the class

public class Person {
    public String name;
    public int age;
    public int favoriteNumber;
}

serialized to the follow JSON:

{ "name": "Joe", "age": 25, "favoriteNumber": "123" }

Note that age=25 is encoded as a number while favoriteNumber=123 is encoded as a string. Out of the box Jackson marshalls int to a number. In this case I want favoriteNumber to be encoded as a string.

like image 471
Steve Kuo Avatar asked Aug 20 '12 23:08

Steve Kuo


2 Answers

You can implement a custom serializer as follows:

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


public class IntToStringSerializer extends JsonSerializer<Integer> {

    @Override
    public void serialize(Integer tmpInt, 
                          JsonGenerator jsonGenerator, 
                          SerializerProvider serializerProvider) 
                          throws IOException, JsonProcessingException {
        jsonGenerator.writeObject(tmpInt.toString());
    }
}

Java should handle the autoboxing from int to Integer for you.

like image 184
Kevin Bowersox Avatar answered Oct 11 '22 21:10

Kevin Bowersox


Jackson-databind (at least 2.1.3) provides special ToStringSerializer (com.fasterxml.jackson.databind.ser.std.ToStringSerializer)

Example:

public class Person {
    public String name;
    public int age;
    @JsonSerialize(using = ToStringSerializer.class)
    public int favoriteNumber:
}
like image 63
werupokz Avatar answered Oct 11 '22 21:10

werupokz