riddy riddy - 1 year ago 145
Java Question

How to automatically parse String @RequestBody as json

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

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)?

Answer Source

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 us its asText method to retrieve its text value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download