使用 Jackson 进行动态序列化 - 删除带有特定注释的字段 [英] Dynamic serialization using Jackson - removing fields with specific annotations
问题描述
走上了创建注释的道路,该注释将动态确定是否应序列化字段.
Went down a path of creating an annotation that would dynamic determine whether a field should be serialized or not.
注解的实现如下:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = HiddenFieldSerializer.class)
@Target(value = ElementType.FIELD)
public @interface Hidden {
}
现在是序列化程序的代码:
Now the code for the Serializer:
public class HiddenFieldSerializer
extends StdSerializer<String>
implements ContextualSerializer {
public HiddenFieldSerializer() {
super(String.class);
}
@Override
public void serialize(String value,
JsonGenerator jgen,
SerializerProvider provider) {
try {
provider.defaultSerializeNull(jgen);
} catch (IOException e) {
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov,
BeanProperty property) {
return shouldHide() ?
new HiddenFieldSerializer() : new StringSerializer();
}
public boolean shouldHide() {
/* Simplifying this */
return Boolean.TRUE;
}
}
一些代码来展示它是如何工作的:
A little bit of code to show how it works:
public class Test {
static final ObjectMapper mapper = new ObjectMapper()
.setSerializationInclusion(Include.NON_NULL)
.setSerializationInclusion(Include.NON_EMPTY);
static class User {
@JsonProperty
String username;
@Hidden
@JsonProperty
String pin;
}
public static void main(String... args)
throws JsonProcessingException {
final POC.User u = new POC.User();
u.username = "harry_potter";
u.pin = "1298";
System.out.println(mapper.writeValueAsString(u));
}
}
输出如下:
{"username":"harry_potter","pin":null}
如何从序列化中删除字段 pin 而不是 null?显然,在这种情况下设置映射器的属性的用户很少.有什么建议?想法?也许整件事是个坏主意?
How do I get the field pin to be removed from the serialization instead of it being null? Obviously setting the mapper's properties was of very little user in such a context. Any suggestions? Thoughts? Maybe the whole thing is a bad idea?
理想情况下,我应该能够看到以下内容:
Ideally I should be able to see the following:
{"username":"harry_potter"}
推荐答案
不清楚是要静态还是动态忽略给定的属性.无论如何,看起来你已经过度设计了.
It's not clear whether you want to ignore a given property statically or dynamically. Anyways, looks like you have over-engineered it.
首先,我想确保您遇到了 @JsonIgnore
之前.如果它不适合您的需求,您可以定义您的自定义忽略注释如下:
First of all, I want to make sure that you came across @JsonIgnore
before. If it doesn't suit your needs, you could define your custom ignore annotation as following:
@Retention(RetentionPolicy.RUNTIME)
public @interface Hidden {
}
然后选择最适合您需求的方法:
Then pick the approach that best suit your needs:
扩展JacksonAnnotationIntrospector
并覆盖检查忽略标记的方法:
Extend JacksonAnnotationIntrospector
and override the method that checks for the ignore marker:
public class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
return super.hasIgnoreMarker(m) || m.hasAnnotation(Hidden.class);
}
}
配置ObjectMapper
使用您的注释内省器:
Configure ObjectMapper
to use your annotation introspector:
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new CustomAnnotationIntrospector());
注解内省每个类仅发生一次,因此您无法动态更改您使用的标准(如果有).在这个答案中可以看到一个类似的例子.
The annotation introspection occurs only once per class so you can not dynamically change the criteria you use (if any). A similar example can be seen in this answer.
扩展BeanSerializerModifier
修改将被序列化的属性:
Extend BeanSerializerModifier
to modify the properties that will be serialized:
public class CustomBeanSerializerModifier extends BeanSerializerModifier {
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
return beanProperties.stream()
.filter(property -> property.getAnnotation(Hidden.class) == null)
.collect(Collectors.toList());
}
}
然后将其添加到 Module
并将其注册到您的 ObjectMapper
:
Then add it to a Module
and register it to your ObjectMapper
:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new SimpleModule() {
@Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.addBeanSerializerModifier(new CustomBeanSerializerModifier());
}
});
这种方法允许您动态忽略属性.
This approach allows you to ignore properties dynamically.
这篇关于使用 Jackson 进行动态序列化 - 删除带有特定注释的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!