0

I have this JSON:

{
   "Date": "3/6/17",
   "Place": "MyPlace",
   "Questions": [{
       "Category": "",
       "Question": "???",
       "Answer": ""
   }, {
       "Category": "",
       "Question": "??? ",
       "Answer": ""
   }, {
       "Category": "",
       "Question": "???",
       "Answer": ""
   }]
}

I want to parse this JSON and get the array inside it as a list.
Using var list = JsonConvert.DeserializeObject<List<JToken>>(jsonString); doesn't work because the thing as a whole isn't an array, only inside it there is an array.
So how do I do this in C#?

amitairos
  • 2,797
  • 10
  • 43
  • 82

2 Answers2

3

You could define the following classes:

public class Question
{

    [JsonProperty("Category")]
    public string Category { get; set; }

    [JsonProperty("Question")]
    public string Question { get; set; }

    [JsonProperty("Answer")]
    public string Answer { get; set; }
}

public class QuestionsDatePlace
{
    [JsonProperty("Date")]
    public string Date { get; set; }

    [JsonProperty("Place")]
    public string Place { get; set; }

    [JsonProperty("Questions")]
    public IList<Question> Questions { get; set; }
}

and then desrialize your json as below:

var list = JsonConvert.DeserializeObject<QuestionsDatePlace>(jsonString);
Christos
  • 52,021
  • 8
  • 71
  • 105
1

The easiest way, without creating additional classes it's:

dynamic json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
var list = json["Questions"];

If you need to cast the result as a sequence of JToken objects then do this.

dynamic json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
var list = ((IEnumerable<dynamic>)json["Questions"]).Select(q => new JToken()
{
    Category = q["Category"],
    Question = q["Question"],
    Answer = q["Answer"]
});

For the record, this required adding the assembly System.Web.Extensions in References node of Solution Explorer.

derloopkat
  • 5,980
  • 15
  • 38
  • 42