Implicit parse LocalDate with Post @Consumes(MediaType.ApplicationJson)

半腔热情 提交于 2019-12-11 02:36:51

问题


this is my Endpoint in which I would like to add a "Firma" with a post request, but the JSON cannot implicit parse the timestamp.

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

Those are the variables of "Firma"

private int firm1;
private LocalDate firm2;

And this is the JSON-String I sent - LocalDate is NULL

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

But whenever I use the get Request with test data, it will show me the right result:

@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();
}

Please help someone.


回答1:


If you are using Jackson, add the following dependency to your project:

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

Then create a ContextResolver for ObjectMapper and register the 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;
    }
}


来源:https://stackoverflow.com/questions/48172558/implicit-parse-localdate-with-post-consumesmediatype-applicationjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!