如何排除Jackson不使用注释的字段? [英] How do I exclude fields with Jackson not using annotations?

查看:690
本文介绍了如何排除Jackson不使用注释的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在渲染之前按名称排除某些字段。字段列表是动态的,因此我无法使用注释。

I need to exclude some fields by names before rendering. The list of fields is dynamic, so I can't use annotations.

我尝试创建自定义序列化程序,但我无法在那里获得字段名称。

I've tried to create custom serializer but I can't get field name there.

在GSON中,我使用过 ExclusionStrategy ,但杰克逊没有这样的功能。是否存在等价物?

In GSON I've used ExclusionStrategy, but Jackson has no such functionality. Is there an equivalent?

推荐答案

以下按名称排除字段的示例来自我的博客文章,Gson v Jackson - 第4部分。 (搜索 PropertyFilterMixIn 。)此示例演示如何使用带有 SimpleBeanPropertyFilter的 FilterProvider serializeAllExcept 用户指定的字段名称列表。

The below example of excluding fields by name is from my blog post, Gson v Jackson - Part 4. (Search for the PropertyFilterMixIn.) This example demonstrates using a FilterProvider with a SimpleBeanPropertyFilter to serializeAllExcept a user-specified list of field names.

@JsonFilter("filter properties by name")  
class PropertyFilterMixIn {}  

class Bar  
{  
  public String id = "42";  
  public String name = "Fred";  
  public String color = "blue";  
  public Foo foo = new Foo();  
}  

class Foo  
{  
  public String id = "99";  
  public String size = "big";  
  public String height = "tall";  
}  

public class JacksonFoo  
{  
  public static void main(String[] args) throws Exception  
  {  
    ObjectMapper mapper = new ObjectMapper();  
    mapper.getSerializationConfig().addMixInAnnotations(  
        Object.class, PropertyFilterMixIn.class);  

    String[] ignorableFieldNames = { "id", "color" };  
    FilterProvider filters = new SimpleFilterProvider()  
      .addFilter("filter properties by name",   
          SimpleBeanPropertyFilter.serializeAllExcept(  
              ignorableFieldNames));  
    ObjectWriter writer = mapper.writer(filters);  

    System.out.println(writer.writeValueAsString(new Bar()));  
    // output:  
    // {"name":"James","foo":{"size":"big","height":"tall"}}  
  }  
} 

(注意:相关的API可能会因最近的Jackson版本而略有变化。 )

(Note: The relevant API may have changed slightly with a recent Jackson release.)

虽然示例确实使用了看似不必要的注释,但注释不会应用于要排除的字段。 (为了帮助改变API以简化必要的配置,请不要犹豫,投票决定实施问题 JACKSON- 274

While the example does use a seemingly unnecessary annotation, the annotation is not applied to the fields to be excluded. (To help get the API changed to simplify the necessary configuration a bit, please don't hesitate to vote for implementation of issue JACKSON-274.

这篇关于如何排除Jackson不使用注释的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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