0

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));
3
  • 4
    That is because your json doesn't match your object. Your json clearly specifies that you have an object with a property cat, and inside this property is another object with your Category property, 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 into Dictionary<string, Dictionary<string, Category>>, and if that gives you something, look at the "cat" key and its dictionary, and the Category key and its value of that dictionary. Commented Jan 5, 2019 at 19:25
  • @LasseVågsætherKarlsen I wanted to shorten the code to write here. I updated my question. I already tried CategoryVM class but result is the same. Commented Jan 5, 2019 at 19:35
  • Try Dictionary<string, CategoryVM>. Commented Jan 5, 2019 at 19:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.