(De)与杰克逊一起序列化DateTime(Joda)

时间:2017-06-20 11:45:50

标签: java datetime jackson jodatime

我正在构建一个REST Web服务。有些类的属性类型为DateTime(JodaTime)。

将此对象发送到我的客户端(Javascript)时,我的对象

private DateTime date;

转换为

{ date: { chronology: {}, millis: 1487289600000 } }

问题是我将此对象发送回服务器时出错,因为我无法实例化chronology

我希望有{ date: 1487289600000}之类的东西 - 任何其他格式都可以。

环境

  • jackson-annotations 2.8.8
  • jackson-core 2.8.8
  • jackson-databin 2.8.8
  • jackson-datatype-joda 2.8.8
  • joda-time 2.7

我的上下文解析器是

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperContextResolver() {
        mapper.registerModule(new JodaModule());
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

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

我错过了什么?如果我没有使用ObjectMapperContextResolver,我会得到相同的结果

更新@CássioMazzochiMolin的回答

我添加了jackson-jaxrs-json-provider 2.8.8jackson-jaxrs-base 2.8.8jackson-module-jaxb-annotations 2.8.8

我的上下文解析器现在就像这样

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperContextResolver() {
        mapper.registerModule(new JodaModule());
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

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

我的应用程序配置

@javax.ws.rs.ApplicationPath("/")
public class ApplicationConfig extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<>();
        resources.add(AuthenticationFilter.class);
        resources.add(CORSFilter.class);
        resources.add(ObjectMapperContextResolver.class);
        resources.add(JacksonJsonProvider.class);
        resources.add(ServiceResource.class);
        return resources;
    }
}

我的serviceResource

@Path("service")
public class ServiceResource {

    @Path("/forecast/stocks/{modelId}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Value> getStocks(@PathParam("modelId") String modelId, @QueryParam("startDate") String startDate, @QueryParam("endDate") String endDate) {
        try {
            DateTime datetimeStart = formatStringToDatetime(startDate);
            DateTime datetimeEnd = formatStringToDatetime(endDate);
            return logicClass.getStocks(modelId, datetimeStart, datetimeEnd);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error calling /hydromax/forecast/stocks", e);
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

}

Value对象

public class Value {

    private DateTime date;
    private Float value;

    public Value() {
    }

    //getter and setter

}

更新

我在ApplicationConfig

中添加了以下代码
@Override
public Map<String, Object> getProperties() {
    Map<String, Object> props = new HashMap<>();
    props.put("jersey.config.server.disableMoxyJson", true);
    return props;
}

我的DateTime现已转换为

"date":{"dayOfMonth":16,"dayOfWeek":4,"era":1,"year":2017,"dayOfYear":47,"weekOfWeekyear":7,"secondOfMinute":0,"millisOfSecond":0,"weekyear":2017,"monthOfYear":2,"hourOfDay":10,"minuteOfHour":0,"yearOfEra":2017,"yearOfCentury":17,"centuryOfEra":20,"millisOfDay":36000000,"secondOfDay":36000,"minuteOfDay":600,"millis":1487235600000,"zone":{"fixed":false,"uncachedZone":{"fixed":false,"cachable":true,"id":"Europe/Paris"},"id":"Europe/Paris"},"chronology":{"zone":{"fixed":false,"uncachedZone":{"fixed":false,"cachable":true,"id":"Europe/Paris"},"id":"Europe/Paris"}},"afterNow":false,"beforeNow":true,"equalNow":false} 

我第一次在部署后调用该服务时出现此错误

  

javax.servlet.ServletException:org.glassfish.jersey.server.ContainerException:java.lang.NoClassDefFoundError:com / fasterxml / jackson / module / jaxb / JaxbAnnotationIntrospector

1 个答案:

答案 0 :(得分:1)

您可能错过了应用程序中的jackson-jaxrs-json-provider模块。

此模块是JAX-RS实现的Jackson JSON提供程序,例如Jersey和RESTeasy。

只有在您需要为Jackson JSON提供商自定义ContextResolver时才需要ObjectMapper ObjectMapper。但如果杰克逊提供者没有注册,ContextResolver就不会做任何事情。

以下是您需要的依赖关系:

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.8.8</version>
</dependency>

如果您没有使用Maven,请将jackson-jaxrs-json-provider-2.8.8.jar添加到类路径中。

然后根据您的需要注册JacksonJsonProvider(仅使用杰克逊注释)或JacksonJaxbJsonProvider(同时使用杰克逊和JAXB注释)。