Search code examples
javaspring-bootrestjacksonresttemplate

Is there a way to choose which fields to be serialized and deserialized when using RestTemplate.exchange() with jackson?


I'm new to Spring Boot and now writing an app that consume some restful APIs. However, the API accept different fields in different HTTP request. Now I have used resttemplate's exchange() method (HttpMethod.GET) to deserialize it to a POJO User. However, when updating (HttpMethod.PUT), different class attributes need to be serialized. Simultaneously, when creating (HttpMethod.POST), anthor set of different fields are required. I've tried to use the jackson's annotations to ignore some fields, but they're static. I need a way to decide which fields to be serialized and deserialized according to the HTTP method I use?


Solution

  • Jackson itself has a notion of a @JsonView. You can mark fields with that annotation and when (de)serializing you can tell it to work only with the fields of a specific view e.g. ObjectMapper#writerWithView().

    While SpringMVC does support JsonViews, I don't think RestTemplate does. And even if it did, it may be cleaner to just create 2 different classes and either extend one another or better - use composition together with @JsonUnwrapped. Relying heavily on views may result in more complicated/dirty classes.