Spring REST - String Serialization - bug or feature?

Viewed 96

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.

2 Answers

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);
Related