The string I want to parse:
[
{
id: "new01"
name: "abc news"
icon: ""
channels: [
{
id: 1001
name: "News"
url: "http://example.com/index.rss"
sortKey: "A"
sourceI开发者_如何学编程d: "1"
},
{
id: 1002
name: "abc"
url: "http://example.com/android.rss"
sortKey: "A"
sourceId: "2"
} ]
},
{
id: "new02"
name: "abc news2"
icon: ""
channels: [
{
id: 1001
name: "News"
url: "http://example.com/index.rss"
sortKey: "A"
sourceId: "1"
},
{
id: 1002
name: "abc"
url: "http://example.com/android.rss"
sortKey: "A"
sourceId: "2"
} ]
}
]
Your JSON isn't actually JSON - you need commas after the fields:
[
{
id: "new01",
name: "abc news",
icon: "",
channels: [
{
id: 1001,
....
Assuming you've done that and that you are using JSON.NET, then you'll need classes to represent each of the elements - the main elements in the main array, and the child "Channel" elements.
Something like:
public class Channel
{
public int Id { get; set; }
public string Name { get; set; }
public string SortKey { get; set; }
public string SourceId { get; set; }
}
public class MainItem
{
public string Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public List<Channel> Channels { get; set; }
}
Because there is a mismatch between the C# member naming conventions and the JSON names, you'll need to decorate each member with a mapping to tell the JSON parser what the json fields are called:
public class Channel
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("sortkey")]
public string SortKey { get; set; }
[JsonProperty("sourceid")]
public string SourceId { get; set; }
}
public class MainItem
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
[JsonProperty("channels")]
public List<Channel> Channels { get; set; }
}
Once you've done this, you can parse a string containing your JSON like this:
var result = JsonConvert.DeserializeObject<List<MainItem>>(inputString);
yup, it's JsonConvert.DeserializeObject(json string)
try using JsonConvert.SerializeObject(object) to create the JSON.
精彩评论