spring, get json keys in the controller function - json

i am sending a JSON object to my controller using POST method inside the request body (using post man).
i want to receive the JSON parameters as variables of my controller function
for ample when i send this
{"A":"some a value", "B":"Some b value"}
i want to get them like this in my controller
#RestController
public class UserController {
#RequestMapping(value="/api/some-update-url" , method=RequestMethod.POST)
Boolean updateSomeData(#RequestParam String A, #RequestParam String B) {
.....
}
}
but this is the result of my postman
{
"timestamp": 1490896822946,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MissingServletRequestParameterException",
"message": "Required Gender parameter 'gender' is not present",
"path": "/api/some-update-url"
}
can you help me please
thank you !!

#RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.
If I were to pass email in as a request parameter, for example, I would annotate the method in my controller as such:
#RequestParam(value = "email", required = true) String email
Calling such method would be done like:
http://some.service.url/verification?email=someone#somewhere.com

#RequestParam is used to map POST/GET request parameters. What you are doing is sending JSON as the body of the request. In that case you need to use #RequestBody parameter on one of your Controller's method parameters.
#RequestMapping(value="/api/some-update-url", method=RequestMethod.PUT)
Boolean updateSomeData(#RequestBody MyClass myClass) {
.....
}
You can further read about #RequestBody here:
https://www.javacodegeeks.com/2013/07/spring-mvc-requestbody-and-responsebody-demystified.html

Related

Save Json list of Strings in Spring/H2

I would like to post a simple list of strings to my Spring application:
[
"aaaa",
"bbbb",
"ccc",
"ddd"
]
Do I really need an entity class which matches my #RequestBody or can I do it in an easier way?
One way you can send them would be as request parameters or as request headers or as path variables.
using request parameters -
http://localhost:8080/abc?strings=aaaa,bbbb,ccc,ddd
In the controller, you can get the list of strings using the #RequestParam annotation.
#RequestMapping(value = "/abc")
public void method(#RequestParam List<String> listOfStrings){
//some logic
}
Using path variables -
http://localhost:8080/abc/aaaa,bbbb,ccc,ddd
In the controller
#RequestMapping(value = "/abc/{listOfStrings}")
public void method(#PathVariable List<String> listOfStrings){
//some logic
}

How to accept json data though post in spring boot rest

PostMapping method
#RestController
#RequestMapping("/validate")
public class Validatesimapi {
#PostMapping
public Simoffers validateSim(#RequestBody ???)
}
I want to pass following json object through post request and accept it in validateSim. What should I write at ???.
{
"id": "1234",
"num":"2343335"
}
both the datatypes of id and num is String.
enter code here
It’s as simple as adding a DTO with the fields that you want. The Jackson mapper will map the json to that object.

Validate json values in response body before sending to spring controller to avoid response code 400

My Spring controller accepts application json response body as an object parameter. I don't see where I can intercept the json to validate the values before Spring controller receives it and complains when it doesn't cast.
Example: User sends json to endpoint - /createUser
Expecting: {"username":"johndoe", "pin": 1234}
Receives: {"username": 1234, "pin": "johndoe"}
If string is sent for int or vice versa, server will show status 400. I'd like to validate the data myself and provide a custom json that details the values that are incorrectly set.
Thanks in advance!
You could create your own class for the #RequestBody param in your controller and make a validation on them. You could use some supported annotations or create on your own. But don't forget to put the #Valid next to the #RequestBody, that's the key. E.g
#RestController
public class UserController {
#PostMapping("/users")
ResponseEntity<String> addUser(#Valid #RequestBody User user) {
// persisting the user
return ResponseEntity.ok("User is valid");
}
// standard constructors / other methods
}
For more information, you could find them here validation, create your own validator.

POSTing `JSON` to an `ArrayList` gets the response "Request JSON Mapping Error"

I have a problem POSTing JSON to an ArrayList
I have a class Plan
public class Plan {
private String planId;
private String planName;
:
:
}
and an ArrayList of Plan - PlanList
public class PlanList {
private List<Plan> plans = new ArrayList<Plan>();
:
:
}
I have POST and GET REST APIs
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Plan createPlan(#CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, Plan plan, #HeaderParam("Organization-Id") String organizationIdByService);
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public PlanList createPlans(#CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, PlanList plans, #HeaderParam("Organization-Id") String organizationIdByService);
#GET
#Produces(MediaType.APPLICATION_JSON)
public PlanList retrieveAllPlans(#CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, #HeaderParam("Organization-Id") String organizationIdByService);
When I GET retrieveAllPlans, I get back the following JSON, just as I expect.
{
"plans": [
{
"planId":"1",
"planName":"Plan 1"
},
{
"planId":"2",
"planName":"Plan 2"
},
{
"planId":"3",
"planName":"Plan 3"
}
]
}
POSTing a single Plan, createPlan, works correctly.
However, when I try to POST to createPlans in the same format that the GET returns, I get the response "Request JSON Mapping Error".
Is the JSON incorrectly formatted? Is my REST definition wrong?
Both of your post functions are being mapped to the same http endpoint. There is probably a #Path notation on the class specifying a single endpoint for all its methods and RestEasy is trying to distinguish by http method (post, get, etc..).
You'll need to specify a unique #Path annotation for each post function. Say:
#Path("/plan")
For the first, and
#Path("/plans")
For the second.
The problem is, that when you try to POST to createPlans, the request is being handled by createPlan method, because both methods are handling the same URL.
The soultion is to make two different #Path for these methods.

Spring MVC : post request and json object with array : bad request

I'm trying to retrieve parameters from a http POST request with Spring MVC.
The request contains the following json object (content-type : application/json), which itself contains an array of customObjects :
{
"globalId":"338",
"lines":[
{
"id": "someId",
"lib":"blabla",
...
}
]
}
Here's the code I'm trying to use :
#RequestMapping(method = RequestMethod.POST, value = "/valider")
#ResponseBody
public void valider(final HttpServletRequest request, #RequestParam("globalId") final String globalId, #RequestParam("lines") final MyCustomObject[] lines) {
All I'm getting is a "bad request" error (http 400).
Is it possible to separately retrieve the two parameters "globalId" and "lines" ? Or since they are in the same json object, it has to be treated has a single parameter ? How do you proceed when you have more than one parameter in a Post request ?
I think you're looking for something like `#RequestBody. Create a class to represent your JSON data. In your case, this class will contain two member variables - globalId as a string and lines as an array of the object it represents. Then in your controller method, you will use the #RequestBody annotation on this class type so that Spring will be able to convert the JSON into object. Check the examples below.
http://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/
JQuery, Spring MVC #RequestBody and JSON - making it work together
http://www.techzoo.org/spring-framework/spring-mvc-requestbody-json-example.html
create model object to map your Json data
class DLibrary{
int id;
String lib;
//getters/setters
}
class GLibrary{
int globalId;
List<DLibrary> lines;
//getters/setters
}
Replace your controller code with below
#RequestMapping(method = RequestMethod.POST, value = "/valider")
#ResponseBody
public void valider(#RequestBody GLibrary gLibrary) {
#RequestBody annotation will map Json to Java Object implicitly.
To achieve this spring must require jackson-core and jackson-mapper library included in your application and your Java class should have getter and setters i.e it must follow bean standards.
Indeed, I have to use #RequestBody to get the JSON object.
Quick summary, depending on how the parameters are passed in the http POST body request :
one JSON object (Content-Type: application/json), use #RequestBody to map the json object to a java object
multiple parameters (Content-Type: application/x-www-form-urlencoded), use #RequestParam for each parameter