How to automatically parse String @RequestBody as

2019-05-02 18:24发布

I have an endpoint which should read a string value as body.

@RestController
public class EndpointsController {
   @RequestMapping( method = RequestMethod.PUT, value = "api/{myId}/name", consumes= MediaType.APPLICATION_JSON )
   public String updateName( @PathVariable( MY_ID ) String myId, @RequestBody String name) {

     //will be: "new name"
     //instead of : newname
     return myId;
   }
}

My problem is, that client will call this with "new name" which is correct IMHO but the server reads this with the quotes, because it does not handle the string as a json object. How can I tell Jackson to parse the string as well (same way than it does with Pojos)?

1条回答
等我变得足够好
2楼-- · 2019-05-02 18:35

If you're using Jackson as your JSON parser, you can simply declare your parameter with the type TextNode. This is the Jackson type representing JSON strings.

public String updateName(@PathVariable(MY_ID) String myId, @RequestBody TextNode name) {

You can then use its asText method to retrieve its text value.

查看更多
登录 后发表回答