user2761009
user2761009

Reputation: 85

Deserializing Json var with json.net in c#

I'm trying to process a JSON structure with Json.NET but without any luck.

{
  "Test": [
    {
      "text": "blah...",
      "Id": 6,
      "Date": "2013-04-13T00:00:00"
    },
    {
      "text": "bluuhh...",
      "Id": 7,
      "Date": "2013-02-10T00:00:00"
    }
  ],
  "ErrorCode": 0,
  "Status": 0,
  "StatusString": "Okay",
  "Message": "successfully returned 2 events."
}

Usually I write:

dynamic stuff = JsonConvert.DeserializeObject(json);

How is it possible to make a foreach for text?

Upvotes: 0

Views: 1953

Answers (2)

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

One way is create objects from json by auto generators json2csharp

for your json it gives

public class Test
{
    public string text { get; set; }
    public int Id { get; set; }
    public string Date { get; set; }
}

public class RootObject
{
    public List<Test> Test { get; set; }
    public int ErrorCode { get; set; }
    public int Status { get; set; }
    public string StatusString { get; set; }
    public string Message { get; set; }
}

then you have

RootObject stuff = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Test item in stuff.Test)
{
    //your code
}

Upvotes: 2

I4V
I4V

Reputation: 35353

dynamic stuff = JsonConvert.DeserializeObject(json);
foreach (var item in stuff.Test)
{
    Console.WriteLine("{0} {1} {2}", item.text, item.Id, item.Date);
}

Upvotes: 3

Related Questions