Spring Boot接收Angular订单数据失败:JSON反序列化错误排查
问题排查:Angular向Spring Boot发送订单数据无法正确接收
问题概述
从Angular应用向Spring Boot发送订单数据,客户端创建订单后发送至服务器,但服务器无法正确接收对象。
前端待发送数据(格式验证正确)
{ "user": { "username": "Yomerito", "address": "Aquimerito 1234, Roswell NM 88000", "credit": "4444-0000-0000-0001" }, "cart": [ { "id": 2, "foodName": "Tacos de Barbacoa", "price": 20, "cuisine": "MEXICAN", "description": "Borrego\nasado en horno de piedra ", "isEnabled": "Y", "imageUrl": "tinyurl\n.com/moleVerdeImage" }, { "id": 1, "foodName": "Kebab", "price": 10, "cuisine": "ARAB", "description": "rico Kebab", "isEnabled": "Y", "imageUrl": "tinyurl\n.com/moleVerdeImage" } ], "status": "PENDING" }
Angular 核心代码
1. 订单创建与提交方法
onSubmit(): void { this.purchaseService.postPurchase(this.createOrder()).subscribe({ next: (data: any) => { let retVal = JSON.parse(JSON.stringify(data)) if (retVal === ("OK")) { this.router.navigate(["/purchase"]) } }, error: err => { console.error(err.message) alert("onSubmit error: " + err.message); } }); } createOrder(): IOrden { this.searchService.orden = {user: this.checkoutForm.value, cart: this.searchService.cart, status: "PEND"} }
Spring Boot 后端代码
订单接收Controller
package com.slbootcamp.foodbox.controller; import com.slbootcamp.foodbox.entity.Orden; import com.slbootcamp.foodbox.entity.User; import com.slbootcamp.foodbox.jdbc.OrdenDao; import com.slbootcamp.foodbox.jdbc.UserDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @CrossOrigin(origins ="*", allowedHeaders = "*") @RestController public class OrdenController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired OrdenDao ordenDao; @PostMapping("/cart/placeOrden") public int placeOrden(@RequestBody Orden orden) { // public int placeOrden(@ModelAttribute Orden orden) { logger.info("---------------> Orden: " + orden); return ordenDao.placeOrden(orden); } }
遇到的错误
1. 使用@RequestBody时的反序列化错误
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `com.slbootcamp.foodbox.entity.Cart` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `com.slbootcamp.foodbox.entity.Cart` from Array value (token `JsonToken.START_ARRAY`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 117] (through reference chain: com.slbootcamp.foodbox.entity.Orden["cart"])]
2. 使用@ModelAttribute时的属性空值问题
---------------> Orden: Orden(status=null, cart=null, user=null)
排查指导
- 修正后端实体类字段类型:错误提示明确说明无法将数组反序列化为单个Cart对象,需将
Orden类中的cart字段定义改为List<Cart>或Cart[]类型。 - 修复Angular方法返回值:当前
createOrder()方法没有返回值,导致传给postPurchase的是undefined。修改方法返回创建好的订单对象:createOrder(): IOrden { const orden = {user: this.checkoutForm.value, cart: this.searchService.cart, status: "PEND"}; this.searchService.orden = orden; return orden; } - 校验前后端字段一致性:检查
Orden、User、Cart实体类的字段名与前端JSON键名完全匹配(包括大小写,比如前端foodName对应后端foodName而非foodname);同时注意前端status值为PENDING,但代码中写的是PEND,需确认后端是否兼容该值。 - 确认请求头格式:确保Angular请求的
Content-Type为application/json(HttpClient默认配置),若误用form-data格式,@RequestBody无法解析,@ModelAttribute也需要字段名严格对应。 - 验证实际请求体:通过浏览器开发者工具的Network标签,查看实际发送的请求体是否与控制台打印的一致,排查代码中对象序列化后的潜在差异。
内容的提问来源于stack exchange,提问作者Gianni Fontanot
相关产品推荐
相关产品推荐

