杰克逊过滤掉没有注释的字段 [英] Jackson filtering out fields without annotations

查看:146
本文介绍了杰克逊过滤掉没有注释的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用以下(简化)代码通过 SimpleBeanPropertyFilter 过滤掉序列化中的某些字段:

I was trying to filter out certain fields from serialization via SimpleBeanPropertyFilter using the following (simplified) code:

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();

    SimpleFilterProvider filterProvider = new SimpleFilterProvider().addFilter("test",
            SimpleBeanPropertyFilter.filterOutAllExcept("data1"));
    try {
        String json = mapper.writer(filterProvider).writeValueAsString(new Data());

        System.out.println(json); // output: {"data1":"value1","data2":"value2"}

    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

private static class Data {
    public String data1 = "value1";
    public String data2 = "value2";
}

我使用 SimpleBeanPropertyFilter.filterOutAllExcept(data1 )); 我原以为创建的序列化Json字符串只包含 {data1:value1} ,但是我得到 {data1:value1,data2:value2}

Us I use SimpleBeanPropertyFilter.filterOutAllExcept("data1")); I was expecting that the created serialized Json string contains only {"data1":"value1"}, however I get {"data1":"value1","data2":"value2"}.

如何创建临时作家尊重指定的过滤器(在我的情况下不能重新配置ObjectMapper)。

How to create a temporary writer that respects the specified filter (the ObjectMapper can not be re-configured in my case).

注意:由于我的应用程序中的使用场景,我只接受那些做的答案不要使用杰克逊注释。

Note: Because of the usage scenario in my application I can only accept answers that do not use Jackson annotations.

推荐答案

您通常会注释数据类要应用过滤器:

You would normally annotate your Data class to have the filter applied:

@JsonFilter("test")
class Data {

您已指定不能在课程上使用注释。您可以使用混合来避免注释数据类。

You have specified that you can't use annotations on the class. You could use mix-ins to avoid annotating Data class.

@JsonFilter("test")
class DataMixIn {}

Mixins 必须在 ObjectMapper 上指定,并指定您不想重新配置它。在这种情况下,您始终可以使用其配置复制 ObjectMapper ,然后修改副本的配置。这不会影响代码中其他地方使用的原始 ObjectMapper 。例如,

Mixins have to be specified on an ObjectMapper and you specify you don't want to reconfigure that. In such a case, you can always copy the ObjectMapper with its configuration and then modify the configuration of the copy. That will not affect the original ObjectMapper used elsewhere in your code. E.g.

ObjectMapper myMapper = mapper.copy();
myMapper.addMixIn(Data.class, DataMixIn.class);

然后使用新的 ObjectMapper

String json = myMapper.writer(filterProvider).writeValueAsString(new Data());
System.out.println(json); // output: {"data1":"value1"}

这篇关于杰克逊过滤掉没有注释的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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