Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically parse String @RequestBody as json

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

like image 856
riddy Avatar asked Nov 30 '15 15:11

riddy


People also ask

How to use @requestbody in JSON and XML with @postmapping?

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:

How to convert JSON sent as HTTP body content to Java object?

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.

What is @requestbody annotation in spring?

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.

What is JSON parse in JavaScript?

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.


Video Answer


1 Answers

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.

like image 56
Sotirios Delimanolis Avatar answered Oct 03 '22 21:10

Sotirios Delimanolis