Andrei V Andrei V - 4 months ago 14
JSON Question

Jackson default serializer

I have base class BaseItem like

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


then I have DerivedItem class like

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


How to make DerivedItem to use default Jackson serializer? If thats not possible then how can I make custom serializer that works as default one?

Answer

Try the following

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

This should inform Jackson to use the custom serializer for Base Item but not for DerivedItem.

Edit: The proof is in the pudding

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;
  }

A stupid custom serializer that translates a number to a boolean representing if it a positive number.

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();
    }
  }

Lets try it out

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));
  }

Output:

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