How to properly register a custom JsonSerializer?

Viewed 5780

I am trying to use Ajax posts to a Spring @RestController. Jackson has issues with @Json...Reference annnotations inside the @Entity the posted one inherits from (@Inheritance(strategy = InheritanceType.JOINED)).

I've seen plenty of questions and answers regarding that. As of now, permanently changing the parent entity is not allowed. I do have access to, and can temporarily change, my local copy so I've been able to confirm removing the annotations in the parent could potentially fix it, presumably, at the cost of breaking something else. So, my solution is to implement a custom JsonSerializer.

The problem with that is it doesn't get called; I think I've done it correctly from what I've seen. Here's the relative code:

I register the @Bean in my AppConfig file. I've tried variations for the method body; this is just the most recent one that doesn't work...

@Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    SimpleModule m = new SimpleModule();
    m.addSerializer(Orchard.class, new OrchardSerializer());
    return new Jackson2ObjectMapperBuilder().modules(m);
}

I provide the serializer; the break point below is never triggered...

public class OrchardSerializer extends JsonSerializer<Orchard> {

    @Override
    public Class<Orchard> handledType() {
        return Orchard.class;
    }

    @Override
    public void serialize(Orchard orchard, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) 
    throws JsonProcessingException {
        System.out.println("Break on me...");
    }
}

The entity I'm trying to post...

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@JsonSerialize(using = OrchardSerializer.class)
public class Orchard extends Yard {

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Person> contacts;

    @Column(name = "COUNT")
    private Integer count;

    ...getters/setters
}

How do I register a custom JsonSerializer so it will be called on an Ajax post?

1 Answers
Related