2

I found a very strange behavior in spring rest.

Having an endpoint like the following

@GetMapping("/foo")
public String foo() {
  return "bar";
}

returns the value bar. Sounds correct, but this is not a valid json, the effective result should be "bar" (note the ""). One might argue that spring expects that if a method returns a string, you have already manually serialized the object, but if all other objects are serialized by spring, then i would expect to have a special way to tell that its already serialized but the default way should be to serialize the value.

Maybe i'm missing something here, that's the reason why i didn't created a ticket in the spring issue tracker jet.

  • You need to format the return value to suit your needs. REST just expose an endpoint. – kometen Sep 02 '21 at 08:58
  • 1
    @kometen yes and no, on the one hand i agree, on the other hand, the jackson object mapper is sitting behind it, and should serialize whatever i return, thats basically the point of the whole thing. – Georg Unterberger Sep 02 '21 at 09:02
  • 1
    Does this answer your question? [Spring MVC - How to return simple String as JSON in Rest Controller](https://stackoverflow.com/questions/30895286/spring-mvc-how-to-return-simple-string-as-json-in-rest-controller) – kometen Sep 02 '21 at 09:37

2 Answers2

2

Unregistering the StringHttpMessageConverter as described in this answer should do the trick: https://stackoverflow.com/a/37906098/505621

0

While not really an answer, there are 2 possible workarounds:

Encode it yourself

Just add the required quotation mark explicitly to the response string \".

This could for example be done by using JSONObject.quote(yourString).

Wrapping

Wrap your string into a simple object or custom class. Then Jackson knows what to do with it.

Collections.singletonMap("value", yourString);
Yolgie
  • 268
  • 3
  • 16