Custom Jackson Deserializer Per Endpoint

Viewed 135

I am wondering if there is a way to customize the Jackson Deserializer per method:

@PostMapping("/first")
public void firstMethod(@RequestBody User user)
{
  ...
}
@PostMapping("/second")
public void secondMethod(@RequestBody User user)
{
  ...
}

In each endpoint, a User class is needed. If I understand it correctly, if the HTTP request is sent to an endpoint with data, Jackson parser will call the setters with corresponding names to the attributes in the body data and try and set everything as a 1:1. How do I change how these get set per endpoint.

For example, in firstMethod(), the data body gets mapped to a User class in 1 fashion and in secondMethod(), the data body gets mapped to a User class in another fashion:

const data = {first: 1, second: 2, third: 3}

firstMethod will create a User of

{something: 1, something2: 2, something3: 3}

secondMethod will create a User of:

{something: 3, something2: 1, something3: 2}

As an example.

1 Answers

You could just inject the HttpServletRequest and map the data manually:

@Autowired
ObjectMapper objectMapper;

@PostMapping
public void foo(@RequestBody User user, HttpServletRequest request) {
    JsonNode json = objectMapper.readTree(request.getReader());
    // use JsonNode object to parse / map the data however you want
}

But I suggest you should ask yourself the question: Why?

If you got two different JSON representations for the same Java Class, you probably should use two different Java DTO classes.

Related