JAX-RS json(java.util.Date)序列化上的不同行为 [英] Different behaviour on JAX-RS json (java.util.Date) serialization

查看:172
本文介绍了JAX-RS json(java.util.Date)序列化上的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的应用程序(Jee7)从Wildfly 9.0.1迁移到Wildfly 16.0.0.

I'm migrating my application (Jee7) from Wildfly 9.0.1 to Wildfly 16.0.0.

我注意到在两个wildfly版本上,JAX-RS json(java.util.Date)反序列化的响应都不同.

I noticed different Responses from JAX-RS json (java.util.Date) deserialization on both wildfly version.

是Bug还是Jee规格更改了?

Is it a bug or Jee spec changed?

是否有一种方法可以对整个应用程序进行全局修复?

Is there a way to globally fix it for entire application?

示例类:

@ApplicationPath("/rest")
public class RestConfig extends Application {

}

@Path("/test")
public class TestResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public TestEntity get() {
        return new TestEntity(new Date());
    }
}

public class TestEntity {

    private Date dtTest;

    /* other fields */

    public TestEntity(Date dtTest) {
        super();
        this.dtTest = dtTest;
    }

    public Date getDtTest() {
        return dtTest;
    }


}

Wildfly 9.0.1响应: {"dtTest":1558550586974}

Wildfly 9.0.1 Response: {"dtTest":1558550586974}

Wildfly 16.0.0响应: {"dtTest":"2019-05-22T18:44:47.268Z [UTC]"}

Wildfly 16.0.0 Response: {"dtTest":"2019-05-22T18:44:47.268Z[UTC]"}

我想获得1558550586974的"dtTest"作为Wildfly 16的回复.

I'd like to get 1558550586974 for "dtTest" as response from Wildfly 16.

推荐答案

该解决方案位于 https://developer.jboss.org/thread/279220 .

我将pom.xml依赖项从Jee7更改为Jee8:

I changed pom.xml dependecy from Jee7 to Jee8:

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>

我创建了一个实现ContextResolver的提供程序

I created a provider implementing ContextResolver

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonbDateConfig implements ContextResolver<Jsonb> {  
    private final Jsonb jsonB;  


    public JsonbDateConfig()  
    {  
        JsonbConfig config = new JsonbConfig();  
        config.setProperty(JsonbConfig.DATE_FORMAT, JsonbDateFormat.TIME_IN_MILLIS);  
        jsonB = JsonbBuilder.create(config);  
    }  


    @Override  
    public Jsonb getContext(Class objectType) {  
        return jsonB;  
    }  
}  

这解决了问题.

这篇关于JAX-RS json(java.util.Date)序列化上的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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