Posting json to mvc 4 WebApi controller action. Why doesn't it deserialize my array?
asp.net-mvc-4, asp.net-web-api, c#, json
Solution
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; }
}
Problem
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" } ] } ``` This json validates. 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 ;-) } } ``` 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; } } ``` For completeness sake, here's the TradeOffer class: ``` public class TradeOffer { int OfferedProductId { get; set; } int OfferedQuantity { get; set; } } ``` 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: - its a POST request - the BODY Content Type is "application/json" - I send the json as the Request Payload in the RAW Body 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!)