Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

json - Jackson Object Mapper in spring MVC not working

Every object with Date format is being serialized as a long.

I've read around that I need to create a custom object mapper

and so I did:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        super();
        configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    }

}

I've also registered that custom mapper as a converter

@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(converter());
    addDefaultHttpMessageConverters(converters);
}

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

    return converter;
}

but still, it doesn't work, and I recieve a long as a date.

Any idea what am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to implement your own Dateserializer, just like the following (got it from this tutorial, so props to Loiane, not me ;-) ):

package ....util.json;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class JsonDateSerializer extends JsonSerializer<Date>{

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm "); // change according to your needs 

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

    String formattedDate = dateFormat.format(date);

    gen.writeString(formattedDate);
}

}

then you could just add the following annotation to your Date-Objects and it will persist fine:

@JsonSerialize(using = JsonDateSerializer.class)
public Date getCreated() {
    return created;
}

At least it works with spring 3.2.4 and jackson 1.9.13 here.

edit: Think about using FastDateFormat instead of SimpleDateFormat, for it's the threadsafe-alternative (as mentioned in the comments of Loianes article)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...