发布JSON来MVC 4的WebAPI控制器动作。为什么它不反序列化我的数组? [英] Posting json to mvc 4 WebApi controller action. Why doesn't it deserialize my array?
问题描述
下面已经快把我有点疯狂。我已经发现了几个类似的问题,但他们没有提供一个解决方案。我试图张贴包含几个数据项的JSON对象。其中之一是对象本身的清单。在这里,它是:
The following has been driving me a bit crazy. I have found a couple of similar problems but they did not offer a solution. I am trying to post a json object containing a few data items. One of them is a list of object itself. Here it is:
{
"ClaimType":"Trade",
"ClaimedProductId":"4",
"ClaimingUserId":"2",
"Message":"test",
"TradeOffers":[
{
"OfferedProductId":"7",
"OfferedQuantity":"5"
},
{
"OfferedProductId":"12",
"OfferedQuantity":"2"
}
]
}
这JSON验证。
我的控制器看起来是这样的:
My controller looks like this:
public class ProductController : ApiController
{
[HttpPost]
public void Claim(ClaimViewModel claimViewModel)
{
//do some amazing stuff with the data from the viewmodel.
//sorry guys. This stuff is just tooo cool to be posted here for all to see
//NOT ;-)
}
}
该ClaimViewModel我张贴如下所示:
The ClaimViewModel I am posting looks like this:
public class ClaimViewModel
{
public Claim.ClaimRequestTypes ClaimType { get; set; }
public int ClaimedProductId { get; set; }
public int ClaimingUserId { get; set; }
public string Message { get; set; }
public List<TradeOffer> TradeOffers { get; set; }
}
为了完整起见,这里的TradeOffer类:
For completeness sake, here's the TradeOffer class:
public class TradeOffer
{
int OfferedProductId { get; set; }
int OfferedQuantity { get; set; }
}
我盯着从Javascript发布之前,我喜欢使用Chrome RestConsole来测试这个坏小子,让我可以看看引擎盖下好一点。我提出一个请求,使用以下设置:
Before I staring posting from Javascript, I like to use the Chrome RestConsole to test this bad boy, so I can look a bit better under the hood. I make a request with the following settings:
- 的POST请求
- 正文内容类型是应用/ JSON
- 我发送JSON作为RAW身体 请求负载
那么这里发生了什么:在所有属性上我的 ClaimViewModel
获取反序列化好和容易。但是, TradeOffers
属性被实例化和调试时显示为2(到目前为止好),但对象在这个列表中的值(属性<$计数的列表C $ C> OfferedProductId 和 OfferedQuantity
)始终为0 /零(不为空!)
Then here's what happens: all properties on my ClaimViewModel
get deserialized nice and easy. However, the TradeOffers
property get instantiated and when debugging shows a list with a count of 2 (so far so good) but the values of the objects in this list (properties OfferedProductId
and OfferedQuantity
) are always 0/zero (not null!)
推荐答案
在 TradeOffer
类属性是私有的(在C#中默认的访问修饰符),这使得它无法设置他们从外面。尽量使他们公共
:
Properties in TradeOffer
class are private (default access modifier in C#), which makes it impossible to set them from outside. Try making them public
:
public class TradeOffer
{
public int OfferedProductId { get; set; }
public int OfferedQuantity { get; set; }
}
这篇关于发布JSON来MVC 4的WebAPI控制器动作。为什么它不反序列化我的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!