Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

asp.net - Parse JSON array in C#

I'm trying to parse the following json array

[
    {
        "email": "john.doe@sendgrid.com",
        "timestamp": 1337197600,
        "smtp-id": "<4FB4041F.6080505@sendgrid.com>",
        "event": "processed"
    },
    {
        "email": "john.doe@sendgrid.com",
        "timestamp": 1337966815,
        "smtp-id": "<4FBFC0DD.5040601@sendgrid.com>",
        "category": "newuser",
        "event": "clicked"
    },
    {
        "email": "john.doe@sendgrid.com",
        "timestamp": 1337969592,
        "smtp-id": "<20120525181309.C1A9B40405B3@Example-Mac.local>",
        "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": "john.doe@sendgrid.com",
        "timestamp": 1337197600,
        "smtp-id": "<4FB4041F.6080505@sendgrid.com>",
        "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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...