与杰克逊(De)序列化DateTime(Joda) [英] (De)Serialize DateTime (Joda) with Jackson

查看:103
本文介绍了与杰克逊(De)序列化DateTime(Joda)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a REST webservice. Some classes have an attribute of type DateTime (JodaTime).

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

When sending this object to my client (Javascript), my object

private DateTime date;

转换为

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

The问题是将这个对象发送回服务器时出现错误,因为我无法实例化年代学

The problem is that I have an error when sending this object back to the server because I cannot instantiate chronology

我会喜欢使用类似 {日期:1487289600000} 的东西-其他任何格式都可以使用。

I would like to have something like { date: 1487289600000} - Any other format could work.

环境


  • jackson注释2.8.8

  • jackson-core 2.8.8

  • jackson-databin 2.8.8

  • jackson-datatype-joda 2.8.8

  • joda-time 2.7

  • 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 我有相同的结果

What am I missing ? If I am not using ObjectMapperContextResolver I have the same result

我添加了 jackson-jaxrs-json-provider 2.8.8 jackson-jaxrs-base 2.8。 8 jackson-module-jaxb注释2.8.8

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

My context resolver is now like this

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

我的服务资源

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

}

对象

public class Value {

    private DateTime date;
    private Float value;

    public Value() {
    }

    //getter and setter

}



更新



我在 ApplicationConfig <中添加了以下代码/ code>

Update

I have added the following code inside 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} 

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

And the first time I call the service after deployment, I have this error


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

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


推荐答案

您可能缺少 jackson-jaxrs-json-provider 模块。

You are probably missing the jackson-jaxrs-json-provider module in your application.

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

This module is the Jackson JSON provider for JAX-RS implementations, such as Jersey and RESTeasy.

A ContextResolver 用于 ObjectMapper 仅在您需要自定义 ObjectMapper (用于Jackson JSON提供程序)。但是 ContextResolver 如果未注册Jackson提供商,则不会执行任何操作。

A ContextResolver for ObjectMapper is only required if you need to customize the ObjectMapper for the Jackson JSON provider. But the ContextResolver won't do anything if the Jackson provider is not registered.

这里

<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 到类路径。

If you are not using Maven, add jackson-jaxrs-json-provider-2.8.8.jar to the classpath.

然后注册 JacksonJsonProvider (仅使用Jackson注释)或 JacksonJaxbJsonProvider (同时使用Jackson和JAXB批注)。

Then register JacksonJsonProvider (using only Jackson annotations) or JacksonJaxbJsonProvider (using both Jackson and JAXB annotations), according to your needs.

这篇关于与杰克逊(De)序列化DateTime(Joda)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆