Different behaviour on JAX-RS json (java.util.Date) serialization

倖福魔咒の 提交于 2020-06-16 18:50:27

问题


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

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

Is it a bug or Jee spec changed?

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

Example classes:

@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 Response: {"dtTest":1558550586974}

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

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


回答1:


The solution found at https://developer.jboss.org/thread/279220.

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>

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

And that solved the problem.



来源:https://stackoverflow.com/questions/56263880/different-behaviour-on-jax-rs-json-java-util-date-serialization

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