Save Json list of Strings in Spring/H2 - json

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
}

Related

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.

Spring Rest: Mapping a property of a bean as nested JSON

My Spring REST controller needs to map an object parameter that looks like this:
{
"batchId": 43091,
"domain": "XX",
"code": "XXX",
"effectiveDate": "2020-02-13",
"status": "Y",
"result": [{"ruleName":"name",...]}]
}
I'm having trouble coming up with the DTO to convert this data into. What I have so far looks like this:
#Data
#NoArgsConstructor
#EqualsAndHashCode
public class ValidationResult {
private String result;
private String status;
private String batchId;
private String domain;
private String code;
private String effectiveDate;
}
But result, which contains the embedded JSON, is always null. I don't care about that JSON being mapped, as I'm storing it as a JSON type in the database (Postgresql). But what Java type do I need to declare it to be to get the controller to convert it? I tried making it a javax.json.JsonObject, but that failed.
What we always do with those json inputs is to map those to specific classes. Which means, in your case, result could be a class which itself contains the given fields "ruleName" and their types. Then your Validaton Result containts a private Result result. If naming conventions are quite right the used mapper will be able to convert and map the response to the class and its properties.

spring, get json keys in the controller function

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

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