How to register a custom JsonSerializer?

I am trying to use Ajax posts in Spring @RestController . Jackson has problems with @Json...Reference comments inside @Entity published, inherited from ( @Inheritance(strategy = InheritanceType.JOINED) ).

I have seen many questions and answers about this. At the moment, the prohibition on the constant change of the parent object is prohibited. I have access and temporarily change my local copy, so I was able to confirm the removal of annotations in the parent, maybe fix it, presumably at the cost of hacking something else. So my solution is to implement a custom JsonSerializer .

The problem with this is not caused; I think I did it right from what I saw. Here's the relative code:

I am registering @Bean in my AppConfig file. I tried options for the body of the method; this is the very last 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 a serializer; the breakpoint below never fires ...

 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 publish ...

 @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 to register a custom JsonSerializer so that it is called in an Ajax post?

+5
source share
1 answer

You don't seem to be using Spring Boot. AFAIK Without Spring Download Jackson2ObjectMapperBuilder not detected automatically. If you want to add your own serializer, you must do this in the WebMvcConfigurerAdapter .

 @Configuration @EnableWebMvc public class WebConfiguration extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { SimpleModule m = new SimpleModule(); m.addSerializer(Orchard.class, new OrchardSerializer()); Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder().modules(m); converters.add(new MappingJackson2HttpMessageConverter(builder.build())); } } 
+4
source

Source: https://habr.com/ru/post/1244917/


All Articles