JsonSerialize / JsonDeserialize在Apache Tomcat(TomEE)中不起作用 [英] JsonSerialize / JsonDeserialize not working in Apache Tomcat (TomEE)

查看:115
本文介绍了JsonSerialize / JsonDeserialize在Apache Tomcat(TomEE)中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最新编辑2019-05-31

LATER EDIT 2019-05-31

如果我编写示例 main 方法,该方法实例化一个Item,然后调用 String s = new ObjectMapper()。writeValueAsString(item); ,然后是自定义序列化器 被正确调用 并起作用。

If I write a sample main method which instantiates an Item and then call String s = new ObjectMapper().writeValueAsString(item);, then the custom serializer is called correctly and has effect.

部署整个应用程序时,仅出现问题在Apache TomEE服务器上。

The issue only appears when the whole app is deployed in an Apache TomEE server.

最新编辑 :注释放置的问题(在字段上与在getter上)不是问题,我尝试了各种组合(在getter上的注释,在私有字段上的注释,在公共字段上的注释等)

LATER EDIT: it's not an issue with placement of annotation (on field vs. on getter), I tried various combinations of this (annotation on getter, annotation on private field, annotation on public field, etc...)

代码:

import com.fasterxml.jackson....
// YES, all JSON-related stuff is from fasterxml

@JsonAutoDetect
public class Item {
    private Date lastModified;

    @JsonSerialize(using = CSer.class)
    public Date getLastModified() {
        return lastModified;
    }

    public class CSer extends JsonSerializer<Date> {
        public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            gen.writeString(dateFormat.format(value));
        }
    }
}

// some place else, in a REST service class
    ...
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getItems(... {
        ...
        return Response.ok(result.getData()).build();
        // result.getData() is an ArrayList of "Item" objects.
    }

问题

  • from what I know, the default JSON output format of the date should be the timestamp. In my case, it's not, instead it's yyyyMMddHHmmssZ
  • the custom serializer has no effect, I cannot change the output format of the date, and the serialize method never gets called.

我的 lib 中的杰克逊文件文件夹: jackson-annotations-2.8.0.jar ,jackson-core-2.8.8.jar,jackson-databind-2.8.8.1.jar

The jackson files in my lib folder: jackson-annotations-2.8.0.jar, jackson-core-2.8.8.jar, jackson-databind-2.8.8.1.jar.

我在做什么错了?

谢谢。

推荐答案

可能与放置注释有关在吸气剂上-您可以移动它以反映类似于

It might have something to do with your annotation being placed on the getter - you might move it to reflect something similar to

public class Item {

    @JsonSerialize(using = CSer.class)
    private Date lastModified;

   // ...
}

将Jackson配置为仅使用getter进行序列化。

or you have to configure Jackson to only use getters for serialization.

这篇关于JsonSerialize / JsonDeserialize在Apache Tomcat(TomEE)中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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