Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

JacksonHowToCustomSerializers

Mike Kobit edited this pageDec 18, 2017 ·4 revisions

Jackson How-To: Custom Serializers

Alternative Methods

There are two general mechanisms for enabling fully customized serialization:

  • Make value class (to be serialized) implement interfaceorg.codehaus.jackson.map.JsonSerializableWithType: this is similar to implementingjava.lang.Serializable in that a method (serialize()) of value class is called to handle serialization.
    • NOTE: prior toJackson 1.5, recommended interface wasorg.codehaus.jackson.map.JsonSerializable; but this is now deprecated since it did not support handling of possible additional type information (seeJacksonPolymorphicDeserialization for details).
    • If choosing to use this method, consider starting with a partial implementation such asorg.codehaus.jackson.map.ser.SerializerBase (for any type} ororg.codehaus.jackson.map.ser.ScalarSerializerBase (for serializers that output JSON Strings, Booleans or Number, aka scalar types)
  • Implementorg.codehaus.jackson.map.JsonSerializer to create an external serializer that can be registered to handle values of certain types (or more specifically values of certain properties)

First method is simpler in that no registration is needed: when values of types that implementJsonSerializable are encountered,serialize() method is called to serialize the instance.

Registering external serializers

There are multiple ways to do register external serializers:

  • By using annotations:
  • Classes and methods can be annotated using@JsonSerialize.using (that takes serializer class as argument) to indicate type of serializer to use

With Jackson 1.7 and above

Jackson 1.7 added ability to register serializers and deserializes viaModule interface. This is the recommended way to add custom serializers -- all serializers are considered "generic", in that they are used for subtypes unless more specific binding is found.

The simplest way is to extend SimpleModule, add serializer(s), and register module with ObjectMapper:

    ObjectMapper mapper = new ObjectMapper();    SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));    testModule.addSerializer(new MyCustomSerializer()); // assuming serializer declares correct class to bind to    mapper.registerModule(testModule);

For more advanced handling of types to serializers you may need to implement Module interface directly; this will give more control over exact matching logic. This may be necessary when dealing with generic types (especially Maps and Collections).

With Jackson 1.0 - 1.6

BeforeJackson 1.7, the main method method was:

  • By using custom serializer factory (org.codehaus.jackson.map.SerializerFactory)
    • Either use or extend existing implementation,org.codehaus.jackson.map.ser.CustomSerializerFactory (or even implement one from scratch if it doesn't work for you)
    • Add mappings (from serialized Class to JsonSerializer instance) by callingaddSpecificMapping oraddGenericMapping (check outJavaDocs for explanation on difference)
    • Custom serializer factory needs to be registered withObjectMapper.setSerializerFactory to be used byObjectMapper

Note that starting with1.8,CustomSerializerFactory is deprecated and should not be used.

Specific use cases

Converting null values to something else

(like empty Strings)

If you want to output some other JSON value instead of null (mainly because some other processing tools prefer other constant values -- often empty String), things are bit trickier as nominal type may be anything; and while you could register serializer forObject.class, it would not be used unless there wasn't more specific serializer to use.

But there is specific concept of "null serializer" that you can use as follows:

// Configuration of ObjectMapper:{// First: need a custom serializer providerStdSerializerProvidersp =newStdSerializerProvider();sp.setNullValueSerializer(newNullSerializer());// And then configure mapper to use itObjectMapperm =newObjectMapper();m.setSerializerProvider(sp);// Serialization as done using regular ObjectMapper.writeValue()}// and NullSerializer can be something as simple as:publicclassNullSerializerextendsJsonSerializer<Object>{publicvoidserialize(Objectvalue,JsonGeneratorjgen,SerializerProviderprovider)throwsIOException,JsonProcessingException   {// any JSON value you want...jgen.writeString("");   }}

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp