我在Catalog Endpoint上创建了一个新路径。假设接受Product的JSON表示并将其添加到数据库。
public ProductWrapper insertProduct(HttpServletRequest request, ProductWrapper wrapper)
{
return wrapper;
}
@RequestMapping(value="product",method=RequestMethod.POST)
public ProductWrapper addProduct(HttpServletRequest request, ProductWrapper wrapper){
return insertProduct(request, wrapper);
}
但是当我把JSON放在消息正文中时。它没有保存到我的包装器中。我的JSON看起来像这样:
{
"id": 1,
"name": "Sudden Death Sauce",
"longDescription": "As my Chilipals know, I am never one to be satisfied. Hence, the creation of Sudden Death. When you need to go beyond... Sudden Death will deliver! ",
"retailPrice": {
"amount": "10.99",
"currency": "USD"
},
"primaryMedia": {
"id": 101,
"title": "Sudden Death Sauce Bottle",
"url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Bottle.jpg",
"altText": "primary"
},
"active": true,
"activeStartDate": "2017-01-25T16:32:36.993-0500",
"manufacturer": "Blair's",
"defaultCategoryId": 2002,
"productAttribute": [
{
"id": 1,
"productId": 1,
"attributeName": "heatRange",
"attributeValue": "4"
}
],
"media": [
{
"id": 102,
"title": "Sudden Death Sauce Close-up",
"url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Close.jpg",
"altText": "alt1"
},
{
"id": 101,
"title": "Sudden Death Sauce Bottle",
"url": "/cmsstatic/img/sauces/Sudden-Death-Sauce-Bottle.jpg",
"altText": "primary"
}
]
}
我错过了什么吗?我放了一个断点,它打得很好。包装器已实例化,但所有成员都为null。
答案 0 :(得分:1)
您需要使用wrapper
为@RequestBody
参数添加注释,并在accepts
上添加@RequestMapping
:
@RequestMapping(value="product",method=RequestMethod.POST, accepts="application/json")
public ProductWrapper addProduct(HttpServletRequest request, @RequestBody ProductWrapper wrapper){
return insertProduct(request, wrapper);
}
当您发送请求时,请确保同时发送Content-Type
标头,例如Content-Type=application/json
,以便Spring将其正确序列化。