6

I'm trying to parse the following json array

[
    {
        "email": "[email protected]",
        "timestamp": 1337197600,
        "smtp-id": "<[email protected]>",
        "event": "processed"
    },
    {
        "email": "[email protected]",
        "timestamp": 1337966815,
        "smtp-id": "<[email protected]>",
        "category": "newuser",
        "event": "clicked"
    },
    {
        "email": "[email protected]",
        "timestamp": 1337969592,
        "smtp-id": "<[email protected]>",
        "event": "processed"
    }
]

I've not really used json format before, so it's all a little new. I found I can parse a single element easily, i.e.

{
        "email": "[email protected]",
        "timestamp": 1337197600,
        "smtp-id": "<[email protected]>",
        "event": "processed"
}

dynamic stuff = JsonConvert.DeserializeObject(json);
Response.Write(string.Format("{0} = {1}<br />", "timestamp", stuff.timestamp)); 
//etc

But i'm struggling with how to get the individual elements into an array to loop through.

I though about splitting the sting on },{ but didn't have much luck with that. I imagine there's an easier way i'm missing.

Thank you.

1
  • stuff is an array. Use stuff[i].timestamp Commented Feb 23, 2014 at 20:35

5 Answers 5

8

Just deserialize the JSON as is and loop it...

dynamic stuff = JsonConvert.DeserializeObject(json);

foreach (var s in stuff) 
{
     Console.WriteLine(s.timestamp);
}

Fiddle: http://dotnetfiddle.net/0SthDp

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

Comments

8

You can create a class like this one, to accept all properties from the json string:

public class MyClass
{
    public string email { get; set; }

    public long timestamp { get; set; }

    [JsonProperty("smtp-id")]
    public string smtpid { get; set; }

    public string category { get; set; }

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

As you can notice there is JsonProperty attribute on the smtpid and evt properties, because you can not use the names in the json string as properties in C#.

Then just call the following line:

var list = JsonConvert.DeserializeObject<List<MyClass>>(json);

and you'll get a strongly typed list of objects that matches the json string.

Comments

1

Create these two classes to hold your data:

public class SMTPEvent {
    public string Email { get; set; }
    public long TimeStamp { get; set; }
    public string SmtpId { get; set; }
    public string EventType { get; set; }
}

public class SMTPEvents {
    public List<SMTPEvent> Events { get; set; }
}

Then you can call the following:

dynamic stuff = JsonConvert.DeserializeObject<SMTPEvents>(json);

To iterate you can then use:

foreach(SMTPEvent sEvent in stuff)
{
    //whatever you want to do.
}

The advantage to this approach is having more type safety at run-time whilst having reusable objects if you're going to use them in other parts of your system. If not, you might want to use the simpler dynamic approach as suggested by others.

Also, remember to use the JsonProperty attribute to specify the actual property name as specified in your JSON string if you cannot / are not going to create fields that have the exact name as in your JSON.

Comments

0

Use JSON.Net to do this for you:

Create a class to hold the data (notice the attribute I put on smtp-id to handle characters C# doesn't like):

public class EmailEvent
{
    public string Email { get; set; }
    public int TimeStamp { get; set; }

    [Newtonsoft.Json.JsonProperty(PropertyName="smtp-id")]
    public string SmtpId { get; set; }
    public string Event { get; set; }
    public string Category { get; set; }
}

Then just deserialize it:

var events = Newtonsoft.Json.JsonConvert.DeserializeObject<List<EmailEvent>>(System.IO.File.ReadAllText(@"z:\temp\test.json"));

foreach (var ev in events)
{
    Console.WriteLine(ev.SmtpId);
}

Comments

0

The first level - stuff - is an Array of objects. It is the objects, or elements in said array, which contain a timestamp field.

Consider the following:

dynamic items = JsonConvert.DeserializeObject(json);
foreach(dynamic item in items) {
   /* use item.timestamp */
}

Comments

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.