使用Post @Consumes进行隐式解析LocalDate(MediaType.ApplicationJson)

时间:2018-01-09 16:25:51

标签: java json jax-rs java-time localdate

这是我的终点,我想在其中添加一个" Firma"发帖请求,但JSON无法隐式解析timestamp

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response  addFirma(Firma firma){
    firmaFacade.create(firma);
    return Response.ok().build();
}

这些是" Firma"

的变量
private int firm1;
private LocalDate firm2;
  

这是我发送的JSON-String - LocalDate为NULL

{
"firm1":2,
"firm2":"2017-09-09"
}

但每当我使用带有测试数据的get Request时,它会显示正确的结果:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response  findFirma() {
    List<Firma> list = firmaFacade.findAll();
    GenericEntity<List<Firma>> result = new GenericEntity<List<Firma>>(list) { };
    return Response.ok().entity(result).build();
}

请帮助别人。

1 个答案:

答案 0 :(得分:2)

如果您使用的是杰克逊,请将以下dependency添加到您的项目中:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>${jackson.version}</version>
</dependency>

然后为ContextResolver创建ObjectMapper并注册JavaTimeModule

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper mapper;

    public ObjectMapperContextResolver() {
        this.mapper = createObjectMapper();
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }

    private ObjectMapper createObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return mapper;
    }
}