Skip to content Skip to sidebar Skip to footer

Ajax Response Does Not Parse Localdate

I need to pass Localdate as part of the Ajax response to jquery datatables. LocalDate field does not display its value. Instead it prints [object,Object]. Obviously, it means Local

Solution 1:

I solved it. had to extend SimpleModule from codehaus to implement serialisation/deserialisation for LocalDate. Below is my code:

publicclassLocalDateSimpleModuleextendsSimpleModule{

    publicLocalDateSimpleModule(String name, Version version) {
        super(name, version);
        addSerializer(LocalDate.class, newJsonSerializer<LocalDate>() {
            @Overridepublicvoidserialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider)throws IOException, JsonProcessingException {
                ToStringSerializer.instance.serialize(value, jgen, provider);
            }
        });
        addSerializer(LocalDateTime.class, newJsonSerializer<LocalDateTime>() {
            @Overridepublicvoidserialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider)throws IOException, JsonProcessingException {
                ToStringSerializer.instance.serialize(value, jgen, provider);
            }
        });
        addDeserializer(LocalDate.class, newJsonDeserializer<LocalDate>() {
            @Overridepublic LocalDate deserialize(JsonParser jp, DeserializationContext ctxt)throws IOException, JsonProcessingException {
                return LocalDate.parse(jp.getText());
            }
        });
        addDeserializer(LocalDateTime.class, newJsonDeserializer<LocalDateTime>() {
            @Overridepublic LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt)throws IOException, JsonProcessingException {
                return LocalDateTime.parse(jp.getText());
            }
        });
    }
}

Register this module in servlet-springs.xml

<bean id="objectMapper"class="org.codehaus.jackson.map.ObjectMapper"/>

<beanname="localDateModule"class="packge.LocalDateSimpleModule"><constructor-argname="name"value="LocalDateModule" /><constructor-argname="version"ref="version" /></bean><beanname ="version"class="org.codehaus.jackson.Version"><constructor-argvalue="1"/>//some value
    <constructor-argvalue="1"/><constructor-argvalue="1"/><constructor-argvalue=" "/></bean>

Post a Comment for "Ajax Response Does Not Parse Localdate"