我正在使用 Jaxrs,使用 springboot 1.5.x 创建 Rest 服务。我有一个具有 Instant 属性的 bean。当我打电话给我的服务而不是得到
{
"startTime": {
"epochSecond": 1517243670,
"nano": 986000000
}
}
我想得到一个iso格式的日期,即{"startTime":"2018-01-29T17:51:05"}
public class MyController{
@GET
@Path("/")
public MyBean test();
return new MyBean(Instant.now());
}
public class MyBean{
private Instant startTime;
}
我添加了 java-8-time 依赖项
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.8.7</version>
</dependency>
并尝试了几种方法,但都没有奏效。
@JsonFormat
属性上的注释@JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss") private Instant startTime;
ObjectMapper
在应用程序配置中@Bean @Primary public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.build(); objectMapper.registerModule(); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); return objectMapper; }
使用@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper>{ private final ObjectMapper MAPPER; public ObjectMapperContextResolver() { MAPPER = new ObjectMapper(); SimpleModule module = new SimpleModule(); MAPPER.registerModule(new JSR310Module()); MAPPER.registerModule(new JavaTimeModule()); module.addSerializer(Instant.class, new DateSerializer()); module.addDeserializer(Instant.class, new DateDeserializer()); MAPPER.registerModule(module); MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } @Override public ObjectMapper getContext(Class<?> type) { return MAPPER; }
使用自定义序列化/反序列化
@JsonDeserialize(using=DateDeserializer.class) @JsonSerialize(using=DateSerializer.class) private Instant startTime; public class DateDeserializer extends JsonDeserializer<Instant>{ @Override public Instant deserialize(JsonParser jp, DeserializationContext arg1) throws IOException, JsonProcessingException { return Instant.parse(jp.readValueAs(String.class)); } } public class DateSerializer extends JsonSerializer<Instant> { @Override public void serialize(Instant value, JsonGenerator gen, SerializerProvider sp) throws IOException {...}
我显然在这里遗漏了一些东西。