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)?
To make your method annotated with @PostMapping be able to accept @RequestBody in JSON and XML using the following annotation: Here is how our method with this annotation will look like: If you want your Web Service Endpoint to be able to respond with JSON or XML, then update your @PostMapping annotation to this one:
Like the one below: Notice that the method responsible for handling HTTP POST requests needs to be annotated with @PostMapping annotation. To be able to convert the JSON sent as HTTP Body content into a Java object which we can use in our application we need to use the @RequestBody annotation for the method argument.
annotation. The @RequestBody annotation is applicable to handler methods of Spring controllers. This annotation indicates that Spring should deserialize a request body into an object. This object is passed as a handler method parameter. Under the hood, the actual deserialization is done by one of the many implementations of MessageConverter.
JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With