Jackson2ObjectMapperBuilder不会序列化对象

时间:2018-04-24 10:53:15

标签: java spring-boot serialization jackson jsonserializer

我正在使用Spring Boot,它有自己的Jackson默认序列化。 它在我的任务范围内工作不正确。 所以我想用我自己的自定义序列化器覆盖Jackson的默认序列化。 这是我的代码:

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
    return new Jackson2ObjectMapperBuilder() {
        @Override
        public void configure(ObjectMapper objectMapper) {
            super.configure(objectMapper);
            objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
            SimpleModule simpleModule = new SimpleModule();
            simpleModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeCustomSerializer());
            objectMapper.registerModule(simpleModule);
            objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
        }
    }.serializerByType(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
        @Override
        public void serialize(ZonedDateTime value,
                              JsonGenerator gen,
                              SerializerProvider serializerProvider) throws IOException {
            gen.writeString(value.getNano() + "");
        }
    });
}


private class ZonedDateTimeCustomSerializer extends JsonSerializer<ZonedDateTime> {
    @Override
    public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(value.getNano() + "");
    }
}

正如您所看到的,我尝试了一些案例,例如

  • 通过SimpleModule注册自定义序列化器
  • 覆盖Jackson2ObjectMapperBuilder#serialize

请告诉我如何覆盖默认的Jackson序列号

2 个答案:

答案 0 :(得分:1)

#Slowpokebreakingnews

如果要添加自定义序列化程序-Jackson2ObjectMapperBuilderCustomizer对customize Jackson2ObjectMapperBuilde进行以下操作:

@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer()
{
    return new Jackson2ObjectMapperBuilderCustomizer()
    {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder)
        {
            builder.serializerByType(CustomPojo.class, 
                                     new CustomSerializator<CustomPojo>());
            //affects to all dates in all pojos (I hope :) )
            builder.indentOutput(true).dateFormat(new SimpleDateFormat
                                                  ("yyyy-MM-dd'T'HH:mm:ssXXX"));

        }
    };
}

对于没有Spring-boot的配置,我重写 configureMessageConverters()

@Configuration
@EnableWebMvc
...
public class WebConfig extends WebMvcConfigurerAdapter
{

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) 
    {
        Jackson2ObjectMapperBuilder builder = new CustomObjectMapperBuilder();
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }

}

并定义我的 CustomJackson2ObjectMapperBuilder

public class CustomObjectMapperBuilder extends Jackson2ObjectMapperBuilder
{
    @Override
    public void configure(ObjectMapper objectMapper)
    {
        super.configure(objectMapper);

        SimpleModule module = new SimpleModule();
        module.addSerializer(Selective.class, new SelectiveSerializer());

        objectMapper.registerModule(module)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .configure(JsonParser.Feature.ALLOW_COMMENTS, true)
            .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
            .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
            .configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true)
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"));
    }
}

答案 1 :(得分:0)

对于序列化日期格式,您可以执行类似这样的操作

@Component
public class JsonDateSerializer extends JsonSerializer<Date>{
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");//yuor desired format goes here
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}

你也可以像你的豆一样。

你还有另一个选择在你的POJO中做这个

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;