Spring @ResponseBody Jackson JsonSerializer with JodaTime

时光毁灭记忆、已成空白 提交于 2019-12-17 11:43:26

问题


I have below Serializer for JodaTime handling:

public class JodaDateTimeJsonSerializer extends JsonSerializer<DateTime> {

    private static final String dateFormat = ("MM/dd/yyyy");

    @Override
    public void serialize(DateTime date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        String formattedDate = DateTimeFormat.forPattern(dateFormat).print(date);

        gen.writeString(formattedDate);
    }

}

Then, on each model objects, I do this:

@JsonSerialize(using=JodaDateTimeJsonSerializer.class )
public DateTime getEffectiveDate() {
    return effectiveDate;
}

With above settings, @ResponseBody and Jackson Mapper sure works. However, I don't like the idea where I keep writing @JsonSerialize. What I need is a solution without the @JsonSerialize on model objects. Is it possible to write this configuration somewhere in spring xml as a one configuration?

Appreciate your help.


回答1:


Although you can put an annotation for each date field, is better to do a global configuration for your object mapper. If you use jackson you can configure your spring as follow:

<bean id="jacksonObjectMapper" class="com.company.CustomObjectMapper" />

<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" >
</bean>

For CustomObjectMapper:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        setDateFormat(new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
    }
}

Of course, SimpleDateFormat can use any format you need.




回答2:


@Moesio pretty much got it. Here's my config:

<!-- Configures the @Controller programming model -->
<mvc:annotation-driven/>

<!-- Instantiation of the Default serializer in order to configure it -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterConfigurer" init-method="init">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>

<bean id="jacksonObjectMapper" class="My Custom ObjectMapper"/>

<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />

The bit that got me is that <mvc:annotation-driven/> makes its own AnnotationMethodHandler and ignores the one you make manually. I got the BeanPostProcessing idea from http://scottfrederick.blogspot.com/2011/03/customizing-spring-3-mvcannotation.html to configure the one that gets used, and voilà! Works like a charm.




回答3:


Same using JavaConfig of Spring 3:

@Configuration
@ComponentScan()
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter
{

    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters)
    {
        converters.add(0, jsonConverter());
    }

    @Bean
    public MappingJacksonHttpMessageConverter jsonConverter()
    {
        final MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
        converter.setObjectMapper(new CustomObjectMapper());

        return converter;
    }
}



回答4:


If you are using Spring Boot, try this in application.yml :

spring:
    jackson:
       date-format: yyyy-MM-dd
       time-zone: Asia/Shanghai
       joda-date-time-format: yyyy-MM-dd



回答5:


If you simply have the Jackson JARs on your classpath, and return a @ResponseBody, Spring will automatically convert the Model object to JSON. You don't need to annotate anything in the Model to get this to work.



来源:https://stackoverflow.com/questions/10649356/spring-responsebody-jackson-jsonserializer-with-jodatime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!