【问题标题】:how to deserialize this JSON using Newtonsoft.Json C#?如何使用 Newtonsoft.Json C# 反序列化此 JSON?
【发布时间】:2022-12-20 00:05:16
【问题描述】:

如何使用 Newtonsoft.Json C# 反序列化此 JSON?

{
  "catalog": {
    "book": [
      {
        "id": "1",
        "author": "Autho1",
        "title": "GDB",
        "genre": "Kl",
        "price": "15",
        "publish_date": "1999-09-02",
        "description": "desc about book"
      },
      {
        "id": "2",
        "author": "Lil",
        "title": "JS",
        "genre": "DS",
        "price": "3.6",
        "publish_date": "1999-09-02",
        "description": "desc 2."
      }    
    ]
  }
}

我需要将 JSON 反序列化为一个结构,但最后我有 book = nil

【问题讨论】:

  • 你试过什么了?
  • newtonsoft.com/json 的首页提供了一个很好的序列化和反序列化示例。
  • 为什么结构? Class 更适合这些。
  • 步骤 1. 创建一个名为 Book 的类,其中包含所有必要的属性。第 2 步。使用 Book 数组创建一个名为 Catalog 的类,第 3 步。反序列化为类型 Catalog

标签: c# json


【解决方案1】:

好的,如official docs of Newtonsoft.Json 中所述,首先为了良好的代码维护,我们应该创建一个模型来描述 C# 类中的所有(或仅需要域/业务逻辑)数据。 对于您的示例,这是 Book 类

[JsonProperty("book")]
    public class Book
    {
        [JsonProperty("id")]
        public uint ID {get; set;} //GUID is better but, check how it's will be parsed 
        [JsonProperty("author")]
        public string Author {get; set;} // string can be replaced by Author model
        [JsonProperty("title")]
        public string Title {get; set;}
        [JsonProperty("genre")]
        public string Genre {get; set;} // string can be replaced by Enum
        [JsonProperty("price")]
        public double Price {get; set;}
        [JsonProperty("publish_date")]
        public string PublishDate {get; set;} // string can be replaced DateTime
        [JsonProperty("description")]
        public string Description {get; set;}
    }

和目录模型

    public class Catalog
    {
        [JsonProperty("book")]
       public List<Book> Book {get; set;} = new List<Book>();
    }

JsonProperty 属性(某处不需要)用于将默认解析器说成 json 中的字段名称,如果需要对象和顺序(我记得就是这样。

我希望你的问题得到解决,请在下次阅读文档并在你的研究中更加耐心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多