简体   繁体   中英

json deserialization returns null

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 .

You could do it like this, then you would not need CategoryVM :

var obj = JsonConvert.DeserializeObject<JObject>(json);
var category = JsonConvert.DeserializeObject<Category>(obj.First.First["Category"].ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM