assia
assia

Reputation: 71

Date serialization in spring MVC

in my json output Date is rendred as Object, so testing with Postman throw an error: Expected 'u' instead of 'e'

{
    "ao_id":6,
    "code":"AOO N°199-2017 C/T",
    "objet":"Marché Cadre - Travaux de réfection de voiries",
    "date_saisie":new Date(1514851200000)
    }

I annotated my entity class with:

 @Column(name = "date_saisie")
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date date_saisie

How to correctly serialize my date object.. thx,

Upvotes: 1

Views: 1957

Answers (1)

Kedar Joshi
Kedar Joshi

Reputation: 1511

An ideal way would be to configure this with following Jackson configuration -

objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

This will make sure that all of the dates are serialized in a consistent format.

Below is the complete configuration for your reference -

public class JacksonMapper extends ObjectMapper
{
    private static final Logger logger = LogManager.getLogger(JacksonMapper.class);

    public JacksonMapper()
    {
        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        this.disable(SerializationFeature.INDENT_OUTPUT);
        this.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        this.registerModules(new Jdk8Module()); // Enables support for JDK 8 data types e.g. Optional
        this.registerModule(new JavaTimeModule()); // Enables serialization of Java 8 timestamps
    }
}

Use following XML configuration for creating bean of objectmapper -

<bean id="objectMapper" class="config.JacksonMapper" />

Upvotes: 2

Related Questions