6
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

Jacksonでnullのときのシリアライズの設定方法

nullのときは空文字を返すための設定

nullのときのシリアライザークラスを作成

NullValueSerializer
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;

public static class NullValueSerializer extends JsonSerializer<Object> {
        @Override
        public void serialize(Object t, JsonGenerator jsonGenerator, SerializerProvider sp)
        throws IOException, JsonProcessingException {
          jsonGenerator.writeString("");
        }
      }

あとはSerializerProviderに上記をセットしたものを、ObjectMapperのインスタンスにセットする。


import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.StdSerializerProvider;

/ *  */

final ObjectMapper mapper= new ObjectMapper();

StdSerializerProvider serializeProvider = new StdSerializerProvider(); 
serializeProvider.setNullValueSerializer(new NullValueSerializer());

mapper.setSerializerProvider(serializeProvider);
  • 参考

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
6
Help us understand the problem. What are the problem?