Reputation: 406
I showed my snippet below where I am trying to send json
obj as Reuestbody
and my controller could not assign the requested value.
{
"Request":
{
"ReferenceNumber" : "ILT06240123201694516287",
"B_Code" : 1,
"B_Code":"888asdad88",
"Request":"11111111111111111"
}
}
@RequestMapping(value="/GetAccountDetails",method = RequestMethod.POST)
public ResponseEntity<AccountListResponse> GetAccountDetails(@RequestBody @Valid CBSAccountRequest cbsAccountReq
,BindingResult result) {
if(result.hasErrors()) {
throw new InvalidException("Not Valid",result);
}
else {
AccountListResponse accountListResponse=new AccountListResponse();
return new ResponseEntity<AccountListResponse>(accountListResponse, HttpStatus.OK);
}
}
public class CBSAccountRequest {
@NotNull
@Size(min=25,max=25,message="Reference number should have 25 characters")
private String ReferenceNumber;
@NotNull
@Digits(integer=1,fraction = 0 )
private int B_Code;
@NotNull
@Size(min=5,max=5, message="Invalid Branch Code")
private String B_Code;
@NotNull
@Size(min=17,max=17 ,message="Invalid Account Number")
private String Request;
//getters and setters
}
I am getting exceptions because of @Valid
.I go through lot of questions related to it and none of them is working for me. I predicted that the issue may happen because of JSON
object structure. I also tried with below object which also not working.
{
"ReferenceNumber" : "ILT06240123201694516287",
"B_Code" : 1,
"B_Code":"888asdad88",
"Request":"11111111111111111"
}
Upvotes: 0
Views: 6220
Reputation: 1
Also consider this: the Java convention for naming a variable in a POJO demands that the first variable is in lowercase. You can however override this by using the @JsonNaming annotation. Check out these threads: https://stackoverflow.com/questions/38935912/requestbody-is-getting-null-values/38939812#38939812
1: @RequestBody is getting null values and @RequestBody is getting null values
You can also read: Jackson Property Custom Naming Strategy
This thread will also be of help: Case insensitive JSON to POJO mapping without changing the POJO
Upvotes: 0
Reputation: 10017
Problem is Your JSON is INVALID
{
"ReferenceNumber" : "ILT06240123201694516287",
"B_Code" : 1,
"B_Code":"888asdad88",
"Request":"11111111111111111"
}
You have Duplicated key B_Code
in your request payload.
Here is what you can do:
B_Code
in jsonB_Code
in Java, it doesn't match the java naming convention.@JsonProperty
to correct it.Upvotes: 0
Reputation: 6114
It seems to me that you are sending JSON request with a wrong structure. In your JSON the outer "Request" element is redundant. Try to send the following request instead:
{
"ReferenceNumber" : "ILT06240123201694516287",
"B_Code" : 1,
"B_Code":"888asdad88",
"Request":"11111111111111111"
}
BTW, as a suggestion. You can use java naming convention for your fields and you will be still able to map names like "B_Code" to them using @JsonProperty
annotation:
@JsonProperty("B_Code")
String bCode;
Upvotes: 3