0

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?

2 Answers 2

3
dynamic stuff = JsonConvert.DeserializeObject(json);
foreach (var item in stuff.Test)
{
    Console.WriteLine("{0} {1} {2}", item.text, item.Id, item.Date);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks :-) Why use {0} {1} {2}? and how to write it with literal
@user2761009 Just to format the output of Console.WriteLine (If find it easier to read then a + " " + b " " c). If you like: var text = (string)item.text;
2

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
}

1 Comment

Or you can generate a class directly in VS2012 in the edit menu => paste special => paste json as classes guillaumebrout.fr/wp-content/uploads/2012/11/clip_image0011.png

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.