我想以非常“不同的”方式对波纹管波霍进行序列化,波霍:
@Data
public class CustomObject implements Prefillable {
private String scenario;
@Prefilled
private String firstName;
private String lastName;
@Prefilled(scenarios = Scenario.A)
private String phoneNumber;
@Prefilled(scenarios = { Scenario.C, Scenario.D })
private Integer age;
private String prefilledData;
}
我需要根据scenario
字段和@Prefilled
批注来序列化此类。如果字段scenario
包含 A 值,则仅firstName
和phoneNumber
应该被序列化。如果将序列化为 C 或 D ,则应为字段firstName
和age
。属性值来自数据库。
我最终得到下面的代码:
可预填充:
@JsonAutoDetect(
fieldVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
creatorVisibility = JsonAutoDetect.Visibility.NONE
)
public interface Prefillable {
String getScenario();
String getPrefilledData();
}
@预填充:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = PrefilledSerializer.class, include = JsonSerialize.Inclusion.NON_EMPTY)
public @interface Prefilled {
Scenario[] scenarios() default { Scenario.A, Scenario.B, Scenario.C, Scenario.D };
}
PrefilledSerializer:
public class PrefilledSerializer extends JsonSerializer implements ContextualSerializer {
private List<Scenario> allowedScenarios;
private Scenario currentScenario;
public PrefilledSerializer() {
}
private PrefilledSerializer(final List<Scenario> allowedScenarios) {
this.allowedScenarios = allowedScenarios;
}
@Override
public void serialize(final Object value, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException {
Object aggregatingObject = jsonGenerator.getCurrentValue();
if (aggregatingObject instanceof Prefillable) {
currentScenario = Scenario.from(((Prefillable) aggregatingObject).getScenario());
if (allowedScenarios != null) {
if (allowedScenarios.contains(currentScenario)) {
jsonGenerator.writeObject(value);
}
}
}
}
@Override
public boolean isEmpty(final SerializerProvider provider, final Object value) {
return super.isEmpty(provider, value);
//Here I have problem
//return !allowedScenarios.contains(currentScenario);
}
@Override
public JsonSerializer<?> createContextual(final SerializerProvider serializerProvider, final BeanProperty beanProperty) {
Prefilled annotation = null;
List<Scenario> channels = null;
if (beanProperty != null) {
annotation = beanProperty.getAnnotation(Prefilled.class);
}
if (annotation != null) {
channels = new ArrayList<>(Arrays.asList(annotation.scenarios()));
}
return new PrefilledSerializer(channels);
}
}
我用它作为休假:
ObjectMapper objectMapper = new ObjectMapper();
customObject.setPrefilledData(objectMapper.writeValueAsString(customObject));
生成的JSON如下所示:
{
"firstName":"Name",
"phoneNumber":"123456789",
"age"
}
这意味着它是无效的...谁知道,我怎么防止我的自定义序列化器序列化 age 字段。我知道,我可以覆盖isEmpty
方法,但是在其中我无权访问聚合对象和当前方案。我想避免反思。