Skip to content
Advertisement

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

JavaScript

serialized to the follow JSON:

JavaScript

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.

Advertisement

Answer

You can implement a custom serializer as follows:

JavaScript

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement