杰克逊默认序列化器

时间:2016-08-02 23:40:13

标签: json serialization jackson

我有基类BaseItem,如

@JsonSerialize(using = MyCustomSerializer.class)
class BaseItem {
  ...
}

然后我有DerivedItem类,如

@JsonSerialize(using = ???.class)
class DerivedItem extends BaseItem {
  ...
}

如何让DerivedItem使用默认的Jackson序列化程序?如果那不可能那么我怎样才能使自定义序列化器成为默认序列化器呢?

1 个答案:

答案 0 :(得分:1)

尝试以下

@JsonSerialize(using = JsonSerializer.None.class)
class DerivedItem extends BaseItem {
  ...
}

这应该告知Jackson使用基本项的自定义序列化程序,但不能使用DerivedItem。

编辑:证据在布丁中

BaseItem.java

  @JsonSerialize(using = BaseSerializer.class)
  public class BaseItem {
    public BaseItem(int x) {
      this.x = x;
    }
    public int getX() {
      return x;
    }
    public void setX(int x) {
      this.x = x;
    }

    int x;
  }

DerivedItem.java

@JsonSerialize(using = JsonSerializer.None.class)
  public class DerivedItem extends BaseItem {
    public DerivedItem(int x, int y) {
      super(x);
      this.y = y;
    }

    public int getY() {
      return y;
    }
    public void setY(int y) {
      this.y = y;
    }

    int y;
  }

一个愚蠢的自定义序列化程序,它将数字转换为一个布尔值,表示它是否为正数。

public class BaseSerializer extends JsonSerializer<BaseItem> {
    @Override
    public void serialize(BaseItem value,
                          JsonGenerator jgen,
                          SerializerProvider provider) throws IOException {
      jgen.writeStartObject();
      jgen.writeBooleanField("x", value.getX() > 0);
      jgen.writeEndObject();
    }
  }

让我们尝试一下

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    BaseItem baseItem = new BaseItem(1);
    DerivedItem derivedItem = new DerivedItem(1,2);
    System.out.println("Base Item: " + mapper.writeValueAsString(baseItem));
    System.out.println("Derived Item: " + mapper.writeValueAsString(derivedItem));
  }

输出:

Base Item:{"x":true}
Derived Item:{"x":1,"y":2}