在C#中解析JSON数组 [英] Parse JSON array in C#
问题描述
我正在尝试解析以下json数组
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"
}
]
我以前并没有真正使用过json格式,所以它有点新.我发现我可以轻松解析单个元素,即
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.
谢谢.
推荐答案
您可以创建一个像这样的类,以接受json字符串中的所有属性:
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; }
}
您可能会注意到smtpid
和evt
属性上有JsonProperty
属性,因为您不能将json
字符串中的名称用作C#
中的属性.
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#
.
然后只需调用以下行:
var list = JsonConvert.DeserializeObject<List<MyClass>>(json);
,您将获得与json字符串匹配的对象的强类型列表.
and you'll get a strongly typed list of objects that matches the json string.
这篇关于在C#中解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!