Reputation: 280
This is driving me crazy. I'm working on a REST endpoint in JAX-RS (Glassfish / Jersey). I have a method that's supposed to receive a String, store it and return it. The entire endpoint should consume and produce JSON. But every time I post a String to the method, it's handed to me in escaped form. E.g. if I post:
fetch("http://localhost:8080/myapp/rest/myresource", {
method: "post",
credentials: 'same-origin',
body: JSON.stringify("test\ntest"),
headers: {
"Content-Type": "application/json"
}
})
and the resource is:
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MyResource {
@POST
public String set(@NotNull String value){
// store it
return storedValue;
}
}
then what is stored, and return to the client, is:
"test\ntest"
If, however, I wrap the String in an object:
fetch("http://localhost:8080/myapp/rest/myresource", {
method: "post",
credentials: 'same-origin',
body: JSON.stringify({value: "test\ntest"}),
headers: {
"Content-Type": "application/json"
}
})
with resource
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MyResource {
@XmlRootElement
public static class Wrapper {
public String value;
}
@POST
public String set(@NotNull Wrapper wrapper) {
String value = wrapper.value;
// store it
return storedValue;
}
}
then the value that's stored and returned to the client is
test
test
Am I missing something?
Glassfish 4.1.1
- jersey 2.10.4-0
- json 1.0-0.1
Upvotes: 2
Views: 1929
Reputation: 19
In order to post raw String as JSON using JAX-RS, you can use "@JsonRawValue" provided by fasterxml.jackson
Class ResponseObject {
@JsonRawValue
String jsonString;
...
}
Whenever you send the response object, unescaped json is sent without slashes.
Upvotes: 0
Reputation: 280
It seems this is a feature: when passing Strings, Jackson assumes you're doing the encoding/decoding yourself.
I'll leave this here for future generations.
Upvotes: 1