Serialize abstract class with SuperBuilder using Jackson

316 Views Asked by At

I have following classes:

@NoArgsConstructor
@AllArgsConstructor
@Data
@SuperBuilder
public abstract class Parent {
    private String parentA;
    private String parentB;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
public class ChildOne extends Parent{
    private String childOneA;
    private String childOneB;
}
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
public class ChildTwo extends Parent{
}
Map<Parent, List<String>> parent2Strs = new HashMap<>();
parent2Strs.put(ChildTwo.builder().parentA("A").parentB("B").build(), List.of("1", "2"));
parent2Strs.put(ChildTwo.builder().parentA("C").parentB("D").build(), List.of("1"));

When I call writeValueAsString() method on the parent2Str class, it doesn't print any attribute in parent class.

I tried to use @Jacksonized on the abstract class. But received error:

error: Builders on abstract classes cannot be @Jacksonized (the builder would never be used).

How can I include the fields in Parent class when serialize the child class?

1

There are 1 best solutions below

2
Jan Rieke On

This behavior has nothing to do with Lombok, @SuperBuilder, or @Jacksonized. Jackson simply serializes map keys using the toString() method, because keys in JSON cannot be structured, but must be plain strings.

If you use your POJOs as map values, everything works as expected (and would also work without @SuperBuilder).

@Jacksonized wouldn't have an effect anyway, because it only affects the deserialization, not the serialization.