简体   繁体   中英

Jersey + Jackson - escaping body json string literal

I have a problem with a simple Jaxrs (jersey) endpoint:

@POST
@Consumes("application/json")
@Produces("application/json")
@Path("/test")
public String doSomething(String s) {
...
}

Whenever I use postman to test it with a simple payload such as "test_string" , Jackson escapes leading and trailing double quotes. I then end up with "\\"test_string\\"" in java.

As far as I know, the "test_string" is valid as a json string literal. If I just send test_string (no double quote), it works fine. However, my clients send well-formed Json strings ("test_string")

How can I tell jackson to accept my literals ?

You'll have two options:

1: create your own wrapper class and put is as parameter

public class TestMapper{
@JsonProperty
public String s;
}

2: without Jackson:

JSONObject jsonObj = new JSONObject(s); 
String result=(String) jsonObj.get("test_string");

I am assuming that you have not configured Jersey to auto map the request using Jackson and I dont see you using ObjectMapper to parse JSON in the code you provided. The request is recieved as a String and Jersey escapes the quotations to make it a valid Java String. To avoid this, use ObjectMapper to parse the string as a String.class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM