maryam mohammadbagheri
maryam mohammadbagheri

Reputation: 101

how to define model of JSON.DeserializeObject

I'm a little bit of confused about when I see the JSON visualizer how exactly I have to define the model that JSON deserializes correctly; for example: Example Screenshot

Text:

{"questions":[{"QID":"NEW0","Context":"از چه سنی مبتلا به دیابت شدید؟"},{"QID":"8","Context":"قند خون سه ساعت بعد از وعده غذایی (میانگین قند خونی که در دو روز اخیر اندازه گرفتید)"}]}

I had an array of Javascript Classe (Questions which is made of Question) now I sent it to the controller side and do not have any idea how I have to deserialize it. I've tested these things and none of them worked.

Wrong ones: (Jsonstring is the JSON object in action's arguments)

 var QustionList = JsonConvert.DeserializeObject<Dictionary<int,Ques>>(jsonstring);

 var QustionList = JsonConvert.DeserializeObject<Dictionary<string,Ques>>(jsonstring);

 var QustionList = JsonConvert.DeserializeObject<Dictionary<List<Ques>>(jsonstring);

 var QustionList = JsonConvert.DeserializeObject<Dictionary<Ques>(jsonstring);

Here is Ques:

public class Ques
{
  public string QID { get; set; }
  public string Context{ get; set; }
}

Upvotes: 1

Views: 187

Answers (1)

Matt Searles
Matt Searles

Reputation: 2765

The top level property in your JSON string is "questions", which is an array of objects, therefore you need a top level class to hold that property. eg

    public class Root
    {
        public Question[] Questions { get; set; }
    }

    public class Question
    {
        public string QID { get; set; }
        public string Context { get; set; }
    }
var root = JsonConvert.DeserializeObject<Root>(jsonString);

Upvotes: 2

Related Questions