简体   繁体   中英

Java Spring receiving list of longs prints MismatchedInputException

I use the following PostMapping to receive 3 parameters:

@PostMapping(value = "/createJobs",
         consumes="application/json",
         produces="application/json")
public @ResponseBody ResponseEntity<HttpStatus> createJobs(
        @RequestBody ArrayList<Long> sizes,
        @RequestBody Long accounts,
        @RequestBody Long productId
) {
    
    System.out.println(sizes + " " + accounts + " " + productId);
    try {
        jobService.createJobs(productId, sizes, accounts);
        return ResponseEntity.status(HttpStatus.OK).build();
    }
    catch (final Exception e) {
        LOGGER.error(e.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

I use Angular to send the post request. The data I send looks like this:

{
   "productId":715,
   "sizes":[3,5],
   "accounts":3
}

But after sending the post-request, I receive the following error:

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.util.ArrayList<java.lang.Long>` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<java.lang.Long>` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]]

While it is convenient to put every Request Key on method arguments with @RequestBody , it is advisable to make a generalized class for each Request Model.

eg My Controller:

ResponseEntity<TransactionLog> checkDiscount(HttpServletRequest request, 
                                             @RequestBody RequestCheckDiscount requestBody) {
    // Your code here
}

My Request Model:

public class RequestCheckDiscount {
    private String username;
    private int amount;
    private long time;

    // Standard getters and setters.
}

The key in the body of the POST request should be productId and not product .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM