如何在使用Jackson反序列化时忽略第三方类的某些字段?

blmhpbnm  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(163)

我有一个包含JFreeChart字段的类,比如XYPolygonAnnotation,它包含自身PaintStroke
我可以使用ObjectMapper轻松地将其序列化。但是当我尝试将其反序列化时,我遇到了一些问题,因为PaintStroke是接口,所以不可能为它们提供构造函数。我尝试使用MixIn将其反序列化,但这还不够。

ObjectMapper mapper = new ObjectMapper();
      SimpleModule test = new SimpleModule();
      test.addAbstractTypeMapping(Paint.class, java.awt.Color.class);
      mapper.registerModule(test);
      mapper.registerModule(new Jdk8Module());
      mapper.addMixIn(XYPolygonAnnotation.class, MixInXYPolygonAnnotation.class);

而我的MixIn是:

public abstract class MixInXYPolygonAnnotation {

  public MixInXYPolygonAnnotation(
      @JsonProperty("polygon") double[] polygon,
      @JsonProperty("stroke") Stroke stroke,
      @JsonProperty("outlinePaint") Paint outlinePaint,
      @JsonProperty("fillPaint") Paint fillPaint) {}
}

但是我收到了这个错误消息。
无法识别的字段“rgb”(类java.awt.Color),未标记为可忽略(4个已知属性:“红色”、“蓝色”、“绿色”、“阿尔法”])
这是我的JSON,这是我的JSON中失败的部分。

"polygon":{
                  "notify":true,
                  "toolTipText":null,
                  "url":null,
                  "outlinePaint":{
                     "red":242,
                     "green":114,
                     "blue":0,
                     "alpha":255,
                     "rgb":-888320,
                     "transparency":1,
                     "colorSpace":{
                        "type":5,
                        "numComponents":3,
                        "profile":{
                           "mediaWhitePoint":[
                              0.9504547,
                              1.0,
                              1.0890503
                           ],
                           "matrix":[
                              [

我应该怎么做才能反序列化来自第三方库的接口?我应该忽略一些字段吗?如果是的话,我应该怎么做呢?我想我遗漏了一些东西。
编辑:
所以我补充道:

@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class MixInPaint {
  public MixInPaint(
      @JsonProperty("red") int red,
      @JsonProperty("green") int green,
      @JsonProperty("blue") int blue,
      @JsonProperty("alpha") int alpha) {}
}

我的Map器看起来像这样:

ObjectMapper mapper = new ObjectMapper();
    SimpleModule test = new SimpleModule();
    test.addAbstractTypeMapping(Paint.class, Color.class);
    mapper.registerModule(new Jdk8Module());
    mapper.addMixIn(XYPolygonAnnotation.class, MixInXYPolygonAnnotation.class);
    mapper.addMixIn(Paint.class, MixInPaint.class);
    mapper.registerModule(test);
    mapper.registerModule(new Jdk8Module());
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

但现在我得到了
无法构造org.jfree.chart.annotations.XYPolygonAnnotation的示例,问题:“多边形”参数为空。
我错过了什么?

v8wbuo2f

v8wbuo2f1#

我设法找到了一个解决办法。
我没有直接加载一个XYPolygonAnnotation,而是加载了它的属性,并使用以下构造函数重新创建了该对象:

XYPolygonAnnotation(double[] polygon, Stroke stroke, Paint outlinePaint, Paint fillPaint)

所以我不需要MixIn。对于第三方库中的其他字段,我创建了我自己的版本。我有一个TimeSeries,并创建了SerializedTimeSeries来拥有我自己的构造函数。

相关问题