4

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

kane
  • 5,465
  • 6
  • 44
  • 72
  • i tried to come up with [an answer](https://stackoverflow.com/a/67729997/592355)! xDxD (after 10 years) ..whereas the answer is "no" for the old question, i see a "probably" for yours! :) If you can structure your endpoints by (java, media)"type" (which is "normal" in spring-data-rest), you can have custom objectmapper "per endpoint". – xerx593 May 27 '21 at 21:24
  • That's pretty smart, didn't know you could do that. I upvoted your answer. However, for my purposes, the object being returned is a `Map` and I don't know about changing the media-type. I didn't mention that this was for a graphql endpoint. – kane May 27 '21 at 21:32
  • 1
    I ended up using a custom objectmapper to write the object as a string and changing the return type to String – kane May 27 '21 at 21:32
  • thanks for the upvote! (i think it would also work with `Map`, but rather not generic types `` ..i post my thoughts as answer..shortly;) – xerx593 May 27 '21 at 21:40
  • by "custom" you mean a `new`, local!? ... safe workaround!+1 – xerx593 May 27 '21 at 21:41
  • by "custom", I just mean a different objectmapper than the default one injected by spring. In my particular case, it's actually wrapped in another object that's injected as a bean, but yeah, it could also have been a new local one. – kane May 27 '21 at 21:49
  • Your solution might work for my Map as well, but I'm afraid of doing that in case there is another endpoint that also returns a Map – kane May 27 '21 at 21:50
  • 1
    i get you, kane! :) what you can do in a github playground is maybe not that applicable in "real world"! ...post your solution! it is a "nice hack"! – xerx593 May 27 '21 at 21:58
  • posted my hack below – kane May 28 '21 at 00:25

1 Answers1

1

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());
}
kane
  • 5,465
  • 6
  • 44
  • 72