Reputation: 301
I am trying to Use JSON.NET to parse response from an 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"
}
}
]
}
this is the output of the api. I anonymized everything because of tokens and IDs.
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()));
}
This is the code I am using. The foreach loop never completes, I placed breakpoints in the loop, but only the foreach line executes, then the code stops. What am I doing wrong. I want to iterate through the json response, getting the name and ID for each channel. I got the C# code from another question, and modified it, but I'm not getting any execution of the code.
Upvotes: 1
Views: 82
Reputation: 23511
To deserialize a json with Json.Net, you can use this :
Generate a class with your Json and 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; }
}
And use this line from the doc :
RootObject m = JsonConvert.DeserializeObject<RootObject>(json);
voila.
Upvotes: 2