Mohanraj Mohanraj -3 years ago 131
JSON Question

@Requestbody is not Getting my JSON object Spring-Boot

I showed my snippet below where I am trying to send

json
obj as
Reuestbody
and my controller could not assign the requested value.

REQUESTED JSON OBJECT



{
"Request":
{
"ReferenceNumber" : "ILT06240123201694516287",
"B_Code" : 1,
"B_Code":"888asdad88",
"Request":"11111111111111111"
}
}


Controller



@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);
}
}


Pojo



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"
}

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download