jsonschema2pojo:如何将注释应用于某些字段

问题描述

我正在使用 jsonschema2pojo,我的一些字段需要特殊的序列化/反序列化。我如何在 json 模式中设置它?

这是我目前的架构:

"collegeEducation": {
  "javaJsonView": "com.trp.erd.common.util.Views.InvestmentProfessionalListView","type": "array","position": 37,"items": {
    "$ref": "#/deFinitions/CollegeEducation"
  }
},

并且需要结果属性看起来像这样:

@JsonProperty("collegeEducation")
@JsonView(Views.InvestProfessionalView.class)
@JsonSerialize(using = JsonListSerializer.class)
@JsonDeserialize(using = JsonListDeserializer.class)
@Valid
private List<CollegeEducation> collegeEducation = new ArrayList<CollegeEducation>();

解决方法

这里是关于 jsonschema2pojo 中的自定义注释的 an answer

使用 field::annotate 来注释字段而不是类。

public class SerializationAnnotator extends AbstractAnnotator {

    @Override
    public void propertyField(JFieldVar field,JDefinedClass clazz,String propertyName,JsonNode propertyNode) {
        super.propertyField(field,clazz,propertyName,propertyNode);

        if (propertyName.equals("collegeEducation")) {
            JAnnotationUse annotation;
            annotation = field.annotate(JsonSerialize.class);
            annotation.param("using",JsonListSerializer.class);

            annotation = field.annotate(JsonDeserialize.class);
            annotation.param("using",JsonListDeserializer.class);
        }
    }
}