如何排除 Jackson 不使用注释的字段? [英] How do I exclude fields with Jackson not using annotations?
问题描述
我需要在渲染前按名称排除一些字段.字段列表是动态的,所以我不能使用注释.
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
,但 Jackson 没有这样的功能.有等价的吗?
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 以稍微简化必要的配置,请不要犹豫投票支持 issue 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屋!