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

本文关键字:Net 对象 字符串 JSON 何使用 Json | 更新日期: 2023-09-27 17:55:44

我要解析的字符串:

[
    {
    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"
    } ]
    }
]

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

你的 JSON

实际上不是 JSON - 你需要在字段后面加上逗号:

[
    {
    id: "new01",
    name: "abc news",
    icon: "",
    channels: [
    {
    id: 1001,
       ....

假设您已经这样做并且正在使用 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; }
    }

由于 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; }
    }

完成此操作后,您可以像这样解析包含 JSON 的字符串:

var result = JsonConvert.DeserializeObject<List<MainItem>>(inputString);

是的,它是 JsonConvert.DeserializeObject(json string)

尝试使用 JsonConvert.SerializeObject(object) 来创建 JSON。