Can anyone lead me to examples showing how to convert incoming JSON to a Model in MVC3?
2 Answers
That's already handled for you by the framework.
So you define models:
public class MyViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public Complex Complex { get; set; }
public IEnumerable<Foo> Foos { get; set; }
}
public class Complex
{
public int Id { get; set; }
}
public class Foo
{
public string Bar { get; set; }
}
then a controller action taking this model:
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
...
}
and finally you hammer this controller action with a JSON request matching the structure of your view model:
$.ajax({
url: '@Url.Action("SomeAction")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
id: 1,
name: 'john smith of course, why asking?',
complex: {
id: 3
},
foos: [
{ bar: 'the bar' },
{ bar: 'the baz' },
]
}),
success: function(result) {
alert('hooray');
}
});
1 Comment
MB34
We decided to make the webservice SOAP. No need for JSON.
http://james.newtonking.com/projects/json-net.aspx
I would add more, but the example code is also on that front page.
6 Comments
MB34
I don't want to convert my model TO JSON, I want to convert JSON to my model. I don't see that package doing that.
darethas
You can DEserialize the JSON, then map the data to your model
Darin Dimitrov
Why would you do all that when the framework already handles this for you?
darethas
@DarinDimitrov the OP stated "incoming JSON" In my experience, json.NET has handeled this much easier than the DataContractJsonSerializer or JavaScriptSerializer. Here is a really good writeup of someone consuming Stack Overflow's JSON API freshbrewedcode.com/jonathancreamer/2012/02/07/…
Darin Dimitrov
Who said anything about
DataContractJsonSerializer? ASP.NET MVC doesn't use that. It uses a JsonValueProviderFactory factory based on the JavaScriptSerializer class. And everything's already built-in. The link you provided illustrates the client/consuming part, not the server side JSON to view model conversion part which is what I thought the OP was asking about. |