[英]Issues using Json.NET
我正在嘗試使用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; }
}
並使用doc中的這一行:
RootObject m = JsonConvert.DeserializeObject<RootObject>(json);
瞧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.