I pass JSON object with ajax formdata to Controller. I try to deserialize it to object, but it always returns null. I only can convert it to dynamic, but then cannot convert dynamic to Category class.
public class CategoryVM
{
public Category category { get; set; }
public CategoryImage categoryImage { get; set; }
public CategoryVM()
{
category = new Category();
categoryImage = new CategoryImage();
}
}
Category class
public class Category
{
public string Kategori { get; set; }
public string Kodu { get; set; }
public bool State { get; set; }
}
JSON value:
{
"cat": {
"Category": {
"Kategori": "xxx",
"Kodu": "yyy",
"State": "true"
}
}
}
Controller:
[HttpPost]
public ActionResult AddCat(string cat)
{
dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(cat);
CategoryVM c = JsonConvert.DeserializeObject<CategoryVM >(JsonConvert.SerializeObject(json)); //converts null here
return View();
}
I also tried JsonConvert, but not working for me:
CategoryVM c = JsonConvert.DeserializeObject<CategoryVM>(JsonConvert.SerializeObject(json));
You have an extra level of nesting {"cat": { /* CategoryVM contents */ }}
that is not reflected in your data model. The easiest way to account for this is to deserialize to a wrapper object with a public CategoryVM cat
property, which could be an anonymous type object:
var c = JsonConvert.DeserializeAnonymousType(cat, new { cat = default(CategoryVM) })
.cat.category;
Demo fiddle here.