杰克逊-仅反序列化YAML中的特定字段

时间:2019-07-06 17:49:05

标签: java jackson yaml snakeyaml

我的YAML如下所示

campaign:
  meta:
    version: 1
    name: APT18
    description: Test description
    tag:
      - execution
      - persistence
      - privilege escalation
    reference:
      - https://example.com

我只想解析此YAML中的特定字段(仅用于 name description )。更具体地说,我只想反序列化相应POJO中存在的那些字段。

以下是我目前的POJO

广告系列

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName(value = "campaign")
public class Campaign {
    Map<String, Meta> meta = new LinkedHashMap<>();

}

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Meta {

    private String name;

    private String description;
}

我的主解析器代码

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.disable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES);
mapper.disable(DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Campaign campaign = mapper.readValue(campaignContent, Campaign.class);

当前,我仅需要此YAML的名称和描述。请注意,这些YAML是在不受我们控制的外部源上生成的,因此无法在源上进行修改。我正在考虑为此编写反序列化器,但是我唯一能想到的是

public class MetaDeserializer extends JsonDeserializer<Meta> {
  @Override
  public Program deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectCodec oc = jp.getCodec();
    JsonNode node = oc.readTree(jp);
    final String name = node.get("name").asText();
    final String description = node.get("description").asText();

    return new Meta(name, description);
  }
}

这工作得很好,但是,有没有办法我可以修改它以仅包括POJO中存在的那些字段?

0 个答案:

没有答案