Null value received when i send a request contained an array of enum with Postman to Spring Boot - spring

Postman Request
RequestDTO + response eSexes null
ENUM class ESex

I don't know for what reason, but i solved it changing the name of the variable in the DTO from "eSexes" to "sessi"...very weird

Related

Customise and remove unrequired fields from Zalando problem reponse body in Spring Boot

I am facing an issue where I throw a Zalando problem error on validation of a field in Spring boot. I customized the response body by extending from AbstractThrowableProblem by invoking the super constructor and passing the required fields.
I set the Status field as BAD_REQUEST and then I pass my custom object to the 'parameters' argument which takes a Map.
Till this point, it's fine. I get a 400 BAD_REQUEST Http status code along with the custom map object in the response body.
The problem now here is that a 'status' field also shows up in the response body which is coming since I set it while calling the super constructor.
I want to know how to just have 400 in the Http Status code section only and not in the response body. I just need my custom map object in the response body.
Actual response:
Response Http status code - 400 BAD_REQUEST
Response body -
{
"status": 400,
"appError": "The name field that you filled in has Invalid special characters."
}
Expected response:
{
"appError": "The name field that you filled in has Invalid special characters."
}
The Zalando problem class I wrote is as below:
class MyAppZalandoProblem extends AbstractThrowableProblem {
Map<String, Object> myMap = new HashMap<>();
myMap.put("appError", "The name field that you filled in has Invalid special characters.");
MyAppZalandoProblem() {
super(null, null, Status.BAD_REQUEST, null, null, null, myMap);
}
}
Short answer
You simply can't.
It's not the recommended way to return an HTTP problem: RFC7807
By the way, The Zalando Problem library maintainers have refused to allow such customization.

Spring Rest Service Return Type

I have a rest service in spring which can return a string or a json. For this in my js code while sending the ajax request, i have specified datatype as "*". I wanted to know how can i handle this in spring service
All produces type are available in org.springframework.http.MediaType and for your requirement you can pass */*.
Constant for that is MediaType.ALL_VALUE in java code.
But if you know that your service always return JSON then I prefer to use MediaType.APPLICATION_JSON_UTF8_VALUE instead of MediaType.ALL_VALUE.
you can add attribute " produces" on your RequestMapping annotation:
#RequestMapping(value = "/yourPath", method = GET,
produces = { "application/json", "application/xml",....all what you want as type})

Spring MVC: Can not deserialize instance of out of START_ARRAY token

I have been beating my head against this for a while now and still no joy. I am new to Spring and could really use some help.
I am trying to use Spring Boot to return a list of codes from a DB table. When I call my REST controller from a URL in a browser...
Example URL: localhost:8081/cis/utl/lookupchoice/O.s/
It returns this:
[
{"lookupId":10,"choiceGroup":"O.s","choiceCode":null,"displayLabel":"Pending","hidden":false,"displayOrder":1},
{"lookupId":11,"choiceGroup":"O.s","choiceCode":null,"displayLabel":"Active","hidden":false,"displayOrder":2},
{"lookupId":12,"choiceGroup":"O.s","choiceCode":null,"displayLabel":"Archived","hidden":false,"displayOrder":3},
{"lookupId":13,"choiceGroup":"O.s","choiceCode":null,"displayLabel":"Placeholder","hidden":false,"displayOrder":4}
]
But, I get an error message when trying to run this from a client controller. The call looks like this:
//
//Compiles but does not work
LookupChoice lookupChoice = restTemplate.getForObject(REST_URI+"/utl/lookupchoice/O.s/",
LookupChoice.class);
The error: nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.MyPakage.repository.LookupChoice out of START_ARRAY token
Assuming the error occurs because an array is returned instead of a single object, I changed the code to this:
//
//Does not compile
Iterable<LookupChoice> lookupChoice = restTemplate.getForObject(REST_URI+"/utl/lookupchoice/U.r/",
Iterable<LookupChoice.class>);
But, now I get an error in Intellij. It's indicating that an "Expression expected" for the Iterable<LookupChoice.class> param, and I can't get past this.
Thank you for your time and assistance,
Ed
Thanks for your reply. I opted for this and it all seems to work now. Thanks for your help!
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object[]> responseEntity;
Object[] lookupChoice;
responseEntity = restTemplate.getForEntity(REST_SERVICE_URI+"/utl/lookupchoice/O.s/" , Object[].class);
lookupChoice = responseEntity.getBody();
model.addAttribute("Status", lookupChoice);
The reason it doesn't compile is because it's impossible in Java to pass a class of generic type parameters because they don't exist at runtime.
You have two options here, either use an array (LookupChoice[]) and convert it to a List<LookupChoice> if necessary:
restTemplate.getForObject(url, LookupChoice[]);
Or you can use the ParameterizedTypeReference:
restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<LookupChoice>>() {}).getBody()
It is an interface though, so either subclass it or use an anonymous class like I did in the code example above.
Also, ParameterizedTypeReference only works on the exchange() method if I'm not mistaken, so you'll get a ResponseEntity in stead of your raw object, so you'll have to use the getBody() method.

Webapi model binder not constructing a complex type?

I have this api action :
[Route("~/api/products/{productCode}/price")]
public IHttpActionResult PutProductPrice(string productCode,
PriceBindingModel binding) {
when I send a request to this endpoint with no request body like this :
Accept: application/json
Content-Type: application/json
Content-Length: 0
In the body of the PutProductPrice binding is null. (different from MVC)
I'm used to Model Binder create a PriceBindingModel using it's default parameterless constructor and assigning the values (in this case there is none)
Is this supposed behavoir ? should I check if Model is null in all my api requests ?
I guess this is a bug or some other problem I'm not seeing.
Note: Sending {} (empty object) on the request, makes the BindingModel be created and getting the expected bad request with a failed modelstate. (which I supposed should happen in the first scenario (sending an empty body) as well.
Note 2: doing this in the first line on the controller make it work as expected:
binding = binding ?? new PriceBindingModel();
ideas ?

How to pass parameters on POST requests on Spring-MVC controller method

I am using Spring MVC.
I am sending a POST request from an Ajax context and I sent one parameter. The Content-Type of the request is {'Content-Type':'application/json;'} and in Firefox's Firebug I see the post request is sent with one parameter:
JSON
orderId "1"
Source
{"orderId":"1"}
How can I get it in my controller in the server? The signature of my method is:
#ResponseBody
#RequestMapping(value = "/blahblah", method = RequestMethod.POST)
public void blahblah(#RequestBody(required=false) String orderId ){...
The incoming orderId is always null. Any ideas?
Thanks..
UPDATED: I used {'Content-Type':'application/x-www-form-urlencoded;'} and send my parameters in the following format "orderId=" + id . Also, I changed the server method using #RequestParam String orderId and the value is passed.
I used {'Content-Type':'application/x-www-form-urlencoded;'} and send my parameters in the following format "orderId=" + id .
I changed also the server method using #RequestParam String orderId and the value is passed.

Resources