JAX-RS (Jersey): String from JSON request body still escaped

自闭症网瘾萝莉.ら 提交于 2019-12-11 13:11:23

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36279605/jax-rs-jersey-string-from-json-request-body-still-escaped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!