Hello guys I want to send Array of int and String as RequestBody:
This is the json:
{
"customUiModel": [1, 3, 5],
"user": "user"
}
This is the endpoint code:
#RequestMapping(value = "/save", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public CustomUiModel createCustomUiObject(#RequestBody #Valid int[] customUiModel, String user) {
return customAppService.saveCustom(customUiModel, user);
}
And this is the error :
"message": "JSON parse error: Cannot deserialize instance ofint[]out
of START_OBJECT token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance ofint[]out of START_OBJECT token\n at [Source:
(PushbackInputStream); line: 1, column: 1]", "path": "/custom/save"
I have tried with Array instead this int[] but I have got same error...
Create an object instead of int[], String to hold them,
public class Example {
private int[] customUiModel;
private String user;
}
and change controller method to,
public CustomUiModel createCustomUiObject(#RequestBody #Valid Example exe) {}
Related
This question already has answers here:
Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice
(4 answers)
Closed 2 years ago.
I have this error:
JSON parse error: Cannot deserialize instance of
com.asc.skyalign.service.dto.TaskDataDTO out of START_ARRAY token;
nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of com.asc.skyalign.service.dto.TaskDataDTO out
of START_ARRAY token\n at [Source: (PushbackInputStream); line: 10,
column: 21] (through reference chain:
com.asc.skyalign.service.dto.WorkOrderDTO["taskDataList"])
When post Json API, this is my request :
{
"siteLocationLat": "35.123415",
"workOrderID": "WO-1rmrud5gkdj4r0n6",
"siteId": "NNA-12312312311",
"siteAcessNotes": "No notes",
"siteLocationLong": "128.910283984",
"assignedTo": "ibrahem#test.com",
"timeStamp": 1596738379102,
"email": "ibrahem#test.com",
"taskDataList": [
{
"roll": "2.0",
"azimuth": "120.0",
"tilt": "9.0",
"sectorLocationLat": "35.123451",
"amtImei": "35800121213",
"wakeuUpInterval": "1440",
"sectorID": "NNA-12312312311-1",
"sectorLocationLong": "128.123123",
"taskName": "Install AMT Sector A",
"taskDescription": "Install AMT on Back of the Antenna"
}
]
}
My WorkOrderDto is:
public class WorkOrderDTO implements Serializable {
private List<TaskDataDTO> taskDataList=new ArrayList<TaskDataDTO>();
public List<TaskDataDTO> getTaskDataList() {
return taskDataList;
}
public void setTaskDataList(TaskDataDTO taskDataDTO) {
this.taskDataList.add(taskDataDTO);
}
}
and my WorkOrder Entity is :
public class WorkOrder implements Serializable {
private List<TaskData> taskDataList=new ArrayList<TaskData>();
public List<TaskData> getTaskDataList() {
return taskDataList;
}
public void setTaskDataList(TaskData taskData) {
taskDataList.add(taskData);
}
}
when run my application and request the api and before arrived my controller i see this Exception in postman body :
JSON parse error: Cannot deserialize instance of com.asc.skyalign.service.dto.TaskDataDTO out of START_ARRAY token;
nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of com.asc.skyalign.service.dto.TaskDataDTO out
of START_ARRAY token\n at [Source: (PushbackInputStream); line: 10,
column: 21] (through reference chain:
com.asc.skyalign.service.dto.WorkOrderDTO["taskDataList"])
and this error in Java Idea terminal :
Bad Request: JSON parse error: Cannot deserialize instance of
com.asc.skyalign.service.dto.TaskDataDTO out of START_ARRAY token;
nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of com.asc.skyalign.service.dto.TaskDataDTO out
of START_ARRAY token at [Source: (PushbackInputStream); line: 10,
column: 21] (through reference chain:
com.asc.skyalign.service.dto.WorkOrderDTO["taskDataList"])
public void setTaskDataList(TaskDataDTO taskDataDTO) {
this.taskDataList.add(taskDataDTO);
}
is strange for me, you say that you set the task data list, and you have a taskDataDto in parameter that you add it to the list. WorkOrderDto taskdatalist getter and setter should be something like this
#JsonProperty("taskDataList")
public List<TaskDataList> getTaskDataList() { return taskDataList; }
#JsonProperty("taskDataList")
public void setTaskDataList(List<TaskDataList> value) { this.taskDataList = value; }
Here is my Controller mapping for put request:
#PutMapping("/voteForPostByUser")
public String vote(#RequestParam(value = "postId", required =
true) String postId, #RequestParam(value = "userId", required = true)
Integer userId, #RequestBody Boolean vote) {
BlogPostVoteDTO blogPostVoteDTO = new BlogPostVoteDTO
(postId, userId, vote);
return
this.blogPostService.updateBlogPostVotes(blogPostVoteDTO);
}
When I run the following request from POSTMAN:
http://localhost:8082/microblog/api/voteForPostByUser?postId=5d564a2638195729900df9a6&userId=5
Request Body:
{
"vote" : true
}
I get the following exception
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot deserialize instance of
`java.lang.Boolean` out of START_OBJECT token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of `java.lang.Boolean` out of START_OBJECT token\n
at [Source: (PushbackInputStream); line: 1, column: 1]",
"trace":
"org.springframework.http.converter.HttpMessageNotReadableException: JSON
parse error: Cannot deserialize instance of `java.lang.Boolean` out of
START_OBJECT token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of `java.lang.Boolean` out of START_OBJECT token\n
at [Source: (PushbackInputStream); line: 1, column: 1]\r\n\tat
I is probably something simple, but I don't get what am I missing ?
You just need to send true or false as the body of the request, no need for curly braces or key-value structure
I try on postman using true or false like this.It's ok.
Create a new class for your payload:
class Payload {
Boolean vote;
// maybe some getters/setter here
}
and use it as your RequestBody
#PutMapping("/voteForPostByUser")
public String vote(#RequestParam(value = "postId", required = true) String postId, #RequestParam(value = "userId", required = true) Integer userId, #RequestBody Payload payload) {
boolean vote = payload.vote; //or payload.getVote()
BlogPostVoteDTO blogPostVoteDTO = new BlogPostVoteDTO(postId, userId, vote);
return this.blogPostService.updateBlogPostVotes(blogPostVoteDTO);
}
You expect a boolean from your #RequestBody Boolean vote however JSON sends text. You can either use the Payload class as suggested already but you can also simply change your controller to expect a String like this #RequestBody String vote and convert that string into boolean using Boolean.valueOf(vote) to be able to use it where you need it.
I am trying to send a json long list and take records from db.
My controller is:
#Api(tags = Endpoint.RESOURCE_customer, description = "customer Resource")
#RestController
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public class CustomerResourceController {
private final customerService customerService;
public CustomerResourceController(customerService customerService) {
this.customerService = customerService;
}
#ApiOperation(
value = "Return customer",
response = customerDto.class, responseContainer="List"
)
#PostMapping(value = Endpoint.RRESOURCE_customer_ID)
public List<customerDto> getCustomersByIds(#RequestBody List<Long> ids) {
return customerService.findcustomerIds(ids);
}
}
and client class is:
#Headers("Content-Type: " + MediaType.APPLICATION_JSON_VALUE)
public interface CustomerClient {
#RequestLine("POST /customer/customers/search")
List<LocGrpDto> getCustomersByIds(#RequestBody #Validated List<Long> ids);
}
And i test this service in postman with JSON:
{ "ids": [1,7,8] }
But I get this error:
{
"timestamp": "2018-10-05T13:29:57.645+0000",
"status": 400,
"error": "Bad Request",
"message": "Could not read document: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream#3cb8b584; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream#3cb8b584; line: 1, column: 1]",
"path": "/api/v1/customer/customers/search",
"errors": []
}
What is the problem? Do you see any problem here or it may be caused because of my service class or dto classes ?
Try requesting with the payload [1,7,8], not {"ids": [1,7,8]}.
Your JSON would translate to a request body with the next format.
class Body {
private List<Long> ids;
// constructor, getters and setters
}
For a REST client, you can take a look at RestTemplate.
RestTemplate template;
List<Long> ids;
List<CustomerDto> = template.exchange(
"/customer/customers/search",
HttpMethod.POST,
new HttpEntity<>(ids),
new ParameterizedTypeReference<List<CustomerDto>>() {}).getBody()
I am trying to read json in my spring boot project.
My JSON data is as follows:
[{
"userId":"101"
},
{
"partNum":"aaa"
},
{
"partNum":"bbb"
},
{
"partNum":"ccc"
}]
I have created a DTO class:
public class TcPartDto {
private String userId;
private List<String> partNum;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<String> getPartNum() {
return partNum;
}
}
And I am calling it in my Controller as follows:
#RequestMapping(value = "/volumeinfo", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"})
#ResponseBody
public List<TcPartVolumeDto> volumeinfo(#RequestBody TcPartDto partList) throws Exception {
return tcService.fetchVolumeInfo(partList);
}
But I get the following error:
Through Postman I get this error:
"Could not read document: Can not deserialize instance of
tc.service.model.TcPartDto out of START_ARRAY token\n at [Source:
java.io.PushbackInputStream#5359141a; line: 1, column: 1]; nested
exception is com.fasterxml.jackson.databind.JsonMappingException: Can
not deserialize instance of tc.service.model.TcPartDto out of
START_ARRAY token\n at [Source: java.io.PushbackInputStream#5359141a;
line: 1, column: 1]"
What wrong am I doing?
The DTO you've created does not match the json data it's trying to read.
Based on your DTO sample json should be:
{
"userId" : "someId",
"partNum" : [ "partNum1", "partNum2"]
}
otherwise if json object you're consuming is fixed then DTO should be:
public class MyDTO {
private String userId;
private String partNum;
// ...
}
and with your controller with a parameter of type
List<MyDTO>
You are sending a JSON Array to your public List<TcPartVolumeDto> volumeinfo(#RequestBody TcPartDto partList) method. But it should be deserialize to a single object: TcPartDto partList.
Change your JSON structure to send only a single TcPartDto or make sure your that your volumeinfo method can receive an Array or List.
And you have to change your JSON structure in case you want to send a single object:
{
"userId": 101,
"partNum": [
"aaa",
"bbb",
"ccc"
]
}
As others already pointed out various answers.
if in case this is the json that you want to map without changing the class :
JSON:
[{
"userId":"101"
},
{
"partNum":"aaa"
},
{
"partNum":"bbb"
},
{
"partNum":"ccc"
}]
Class:
#JsonIgnoreProperties(ignoreUnknown=true)
public class TcPartDto {
private String userId;
private List<String> partNum;
//getters and setters
}
Controller:
#RequestMapping(value = "/volumeinfo", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"})
#ResponseBody
public List<TcPartVolumeDto> volumeinfo(#RequestBody TcPartDto[] partArray) throws Exception {
return tcService.fetchVolumeInfo(partArray);
}
Output:
[{"userId":"101","partNum":null},{"userId":null,"partNum":["aaa"]},{"userId":null,"partNum":["bbb"]},{"userId":null,"partNum":["ccc"]}]
Ok, im trying to receive this kind of JSON
[{"username":"pippo","password":"bla"},{"username":"pluto","password":"bla"},{"username":"topolino","password":"bla"}]
But i receive this error:
Resolving exception from handler [public void sequenziatore.server.presenter.LoginController.CheckLogin(java.util.Vector<sequenziatore.server.presenter.Utente>)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.util.Vector out of START_OBJECT token
at [Source: org.apache.catalina.connector.CoyoteInputStream#68c40ef9; line: 1, column: 1]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.Vector out of START_OBJECT token
at [Source: org.apache.catalina.connector.CoyoteInputStream#68c40ef9; line: 1, column: 1]
Resolving exception from handler [public void sequenziatore.server.presenter.LoginController.CheckLogin(java.util.Vector<sequenziatore.server.presenter.Utente>)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.util.Vector out of START_OBJECT token
at [Source: org.apache.catalina.connector.CoyoteInputStream#68c40ef9; line: 1, column: 1]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.Vector out of START_OBJECT token
at [Source: org.apache.catalina.connector.CoyoteInputStream#68c40ef9; line: 1, column: 1]
Resolving exception from handler [public void sequenziatore.server.presenter.LoginController.CheckLogin(java.util.Vector<sequenziatore.server.presenter.Utente>)]: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.util.Vector out of START_OBJECT token
at [Source: org.apache.catalina.connector.CoyoteInputStream#68c40ef9; line: 1, column: 1]; nested exception is org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.Vector out of START_OBJECT token
at [Source: org.apache.catalina.connector.CoyoteInputStream#68c40ef9; line: 1, column: 1]
And this is the controller that im using :
#Controller
#RequestMapping(value = "/login")
public class LoginController {
#RequestMapping(method=RequestMethod.POST, consumes = "application/json", produces = "application/json")
#ResponseBody
public void CheckLogin(#RequestBody Vector<Utente> vec) {
.....
}
I tried to change the type that i receive with Utente[] instead of Vector but nothing changed, and the real problem is that i don t understand what the error is...
This is the JSON that i receive if i change the receiving type in String and print it...
{"0":{"username":"pippo","password":"bla"},"1":{"username":"pluto","password":"bla"},"2":{"username":"topolino","password":"bla"}}
This is the class Utente
public class Utente {
private String username=null;
private String password=null;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Utente(){}
}