我正在尝试使用 JSON.NET 来解析来自API的响应。
{
"ok": true,
"channels": [
{
"id": "xxxxx",
"name": "xx",
"created": "xxxxx",
"creator": "xxxxxx",
"is_archived": false,
"is_member": false,
"num_members": 2,
"is_general": false,
"topic": {
"value": "",
"creator": "",
"last_set": "0"
},
"purpose": {
"value": "",
"creator": "",
"last_set": "0"
}
},
{
"id": "xxxxx",
"name": "xxxxx",
"created": "xxxxxx",
"creator": "xxxxxxx",
"is_archived": false,
"is_member": true,
"num_members": 3,
"is_general": true,
"topic": {
"value": "",
"creator": "",
"last_set": "0"
},
"purpose": {
"value": "xxxxx",
"creator": "",
"last_set": "0"
}
},
{
"id": "xxxx",
"name": "xxxxxxx",
"created": "xxxxxx",
"creator": "xxxxxx",
"is_archived": false,
"is_member": false,
"num_members": 2,
"is_general": false,
"topic": {
"value": "",
"creator": "",
"last_set": "0"
},
"purpose": {
"value": "xxxxxxxxx",
"creator": "",
"last_set": "0"
}
},
{
"id": "xxxx",
"name": "xxxxx",
"created": "xxxxxx",
"creator": "xxxxxx",
"is_archived": false,
"is_member": true,
"num_members": 2,
"is_general": false,
"topic": {
"value": "",
"creator": "",
"last_set": "0"
},
"purpose": {
"value": "xxxxxx",
"creator": "xxxxx",
"last_set": "xxxx"
}
}
]
}
这是 API 的输出。由于令牌和ID,我匿名了所有内容。
JObject root = JObject.Parse(channelJSON);
foreach (JProperty prop in root["channels"].Children<JProperty>())
{
JObject Channel = (JObject)prop.Value;
ChannelList.Add(new SlackChannel(Channel["name"].ToString(), Channel["id"].ToString()));
}
这是我正在使用的代码。foreach 循环永远不会完成,我在循环中放置了断点,但只有 foreach 行执行,然后代码停止。我做错了什么。我想循环访问 json 响应,获取每个通道的名称和 ID。我从另一个问题中获取了 C# 代码,并对其进行了修改,但我没有得到任何代码的执行。
要使用 Json.Net 反序列化 json,您可以使用以下内容:
用你的 Json 和 json2csharp 生成一个类:
public class Topic
{
public string value { get; set; }
public string creator { get; set; }
public string last_set { get; set; }
}
public class Purpose
{
public string value { get; set; }
public string creator { get; set; }
public string last_set { get; set; }
}
public class Channel
{
public string id { get; set; }
public string name { get; set; }
public string created { get; set; }
public string creator { get; set; }
public bool is_archived { get; set; }
public bool is_member { get; set; }
public int num_members { get; set; }
public bool is_general { get; set; }
public Topic topic { get; set; }
public Purpose purpose { get; set; }
}
public class RootObject
{
public bool ok { get; set; }
public List<Channel> channels { get; set; }
}
并使用文档中的这一行:
RootObject m = JsonConvert.DeserializeObject<RootObject>(json);
瞧。