4

I am serializing an instance of a class with Jackson. What is the best way to only serialize the fields of the superclass of this instance?

Currently I have to add the JSONIgnore annotation to every method in my subclass, is there any better way to do that?

Display name
  • 2,697
  • 2
  • 31
  • 49

1 Answers1

3

Assuming you have control of the serialization process directly via ObjectMapper, you can easily accomplish this by creating an ObjectWriter specific to your superclass. Here is some sample code illustrating this.

public class Account implements Serializable {
    private String accountNumber;
    private String routingNumber;
    private BigDecimal balance;

    // Constructors, setters/getters
}

public class SavingsAccount extends Account {
    private BigDecimal savingsRate;

    // Constructors, setters/getters
}


final ObjectMapper mapper = new ObjectMapper();
final ObjectWriter writer = mapper.writerWithType(Account.class);
final ByteArrayOutputStream baos = new ByteArrayOutputStream(6400);
final SavingsAccount account = new SavingsAccount("0031-3402-2189",
    "0009835011203", BigDecimal.valueOf(53500),
     BigDecimal.valueOf(0.3));

writer.writeValue(baos, account);
final String results = new String(baos.toByteArray());
baos.close();

System.out.println(results);

Running the above code illustrates that Jackson writes the superclass fields, even though the runtime instance is of the subclass type.

{"accountNumber":"0031-3402-2189","routingNumber":"0009835011203","balance":53500}

EDIT:

Thanks, but in my case I try to achieve this behaviour for several classes are fields of the outer class that I serialize. Can I define the types more in general?

This scenario is even easier to deal with. Just annotate the appropriate fields in the outer class with @JsonSerialize. If you declare the fields as the superclass type, then set the typing as static. This will flag those fields to Jackson to be serialized using the compile time type as opposed to the runtime type.

On the other hand, if you declare the fields as the subclass type, then set the using as the superclass.

The following example uses the classes I defined further above:

public class BankCustomer implements Serializable {
    @JsonSerialize(typing=Typing.STATIC)
    private Account cdAccount;

    @JsonSerialize(using=Account.class)
    private SavingsAccount savingsAccount;
}
Perception
  • 79,279
  • 19
  • 185
  • 195
  • Thanks, but in my case I try to achieve this behaviour for several classes are fields of the outer class that I serialize. Can I define the types more in general? – Display name Dec 18 '12 at 08:25
  • You might want to explain more specifically, what you are trying to accomplish, in your original question. – Perception Dec 18 '12 at 11:47