问题
I've a Spring Boot application with RESTful endpoints that I want to add custom serializers to for joda-time but I can't get the applications default Jackson serailzier to recognize my custom one's.
I created RESTFul endpoints using @RepositoryRestResource
@RepositoryRestResource(collectionResourceRel = "x", path = "x")
public interface XRepository extends PagingAndSortingRepository<X, Long>
{
}
I then have a GET call to return all object X's:
http://localhost:8181/x
This is my serializer:
@Component
public class JsonDateSerializer extends JsonSerializer<DateTime>
{
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
@Override
public void serialize(DateTime value, JsonGenerator gen,
SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeString(formatter.print(value));
}
}
And I add it to the property Getter as follows:
@JsonSerialize(using=JsonDateSerializer.class)
public DateTime getDateCreated()
{
return dateCreated;
}
This serializer works perfectly in a normal application but when I try to use this in my Spring Boot application these serializers get ignored.
How can I get Spring Boot to recognize these serializers?
回答1:
Ok so after much torment I found out the answer. I was using the wrong library for the serialization and deserialization of the joda-datetime.
I was using
org.codehaus.jackson
when I should have been using
com.fasterxml.jackson
I guess this is an easy mistake as both libraries have almost identical properties and methods because com.fasterxml.jackson is built on top of org.codehaus.jackson.
Silly mistake looking back now but a valuable lesson learnt to ALWAYS check your using the correct library!!!!
回答2:
With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.
Dont use this
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
Use this instead.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
Also use com.fasterxml.jackson.databind.JsonDeserializer and com.fasterxml.jackson.databind.annotation.JsonDeserialize for the deserialization and not the classes from org.codehaus.jackson
来源:https://stackoverflow.com/questions/30376714/spring-boot-ignores-jsondeserialize-and-jsonserialize