Is it possible to customize ObjectMapper for single Spring Rest endpoint?

Viewed 706

I know how to customize the default ObjectMapper bean. But for one specific Controller/endpoint, I'd like to use a different objectmapper. How can I do this?

I think my question is similar to this one but there are no answers yet. Happy to get an answer there and mark this as duplicate

1 Answers

There's a good solution by @xerx593 linked in the question's comments but I took a different approach for mine because I was returning a generic Map<String,Object> graphql return type and I didn't feel comfortable changing the media-type or applying the object mapper to all Map's. I prefer their solution for the general case as it's more elegant

I simply serialized the return object as a string and returned it.

For example, I turned something like this

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public Foo getFoo() {
  return new Foo();
}

to something like this

private ObjectMapper customMapper = ...;

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public String getFoo() {
  return customMapper.writeValueAsString(new Foo());
}
Related