我正在尝试用 Json.NET 处理一个JSON结构,但没有任何运气。
{
"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."
}
通常我写:
dynamic stuff = JsonConvert.DeserializeObject(json);
怎么可能为text
制作foreach
?
dynamic stuff = JsonConvert.DeserializeObject(json);
foreach (var item in stuff.Test)
{
Console.WriteLine("{0} {1} {2}", item.text, item.Id, item.Date);
}
一种方法是通过自动生成器 json2csharp 从 json 创建对象
对于您的 JSON 它提供了
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; }
}
那么你有
RootObject stuff = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Test item in stuff.Test)
{
//your code
}