如何使用Json.Net将JSON字符串解析为.Net对象?

0 c# json.net windows-phone-7

我要解析的字符串:

[
    {
    id: "new01"
    name: "abc news"
    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"
    } ]
    },
{
    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"
    } ]
    }
]
Run Code Online (Sandbox Code Playgroud)

Dam*_*ian 5

您的JSON实际上不是JSON - 您需要在字段后面使用逗号:

[
    {
    id: "new01",
    name: "abc news",
    icon: "",
    channels: [
    {
    id: 1001,
       ....
Run Code Online (Sandbox Code Playgroud)

假设您已经完成了并且您正在使用JSON.NET,那么您将需要类来表示每个元素 - 主数组中的主要元素和子"Channel"元素.

就像是:

    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; }
    }
Run Code Online (Sandbox Code Playgroud)

因为C#成员命名约定和JSON名称之间存在不匹配,所以您需要使用映射来装饰每个成员,以告诉JSON解析器调用json字段:

    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; }
    }
Run Code Online (Sandbox Code Playgroud)

完成此操作后,您可以解析包含JSON的字符串,如下所示:

var result = JsonConvert.DeserializeObject<List<MainItem>>(inputString);
Run Code Online (Sandbox Code Playgroud)