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));
cat, and inside this property is another object with yourCategoryproperty, and inside this property you have an object with the 3 properties you added to your category class. Basically, you're missing a few levels of objects around it. Try deserializing it intoDictionary<string, Dictionary<string, Category>>, and if that gives you something, look at the"cat"key and its dictionary, and theCategorykey and its value of that dictionary.Dictionary<string, CategoryVM>.