如何使用Newtonsoft.JsonC #反序列化这个JSON?

rvpgvaaj  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(125)

如何使用Newtonsoft.JsonC #反序列化这个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

l2osamch

l2osamch1#

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

[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>();
    }

之后你可以做一些

string 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."
      }    
    ]
  }
}";

Catalog catalog = JsonConvert.DeserializeObject<Catalog>(json);

如果需要对象和顺序(我记得仅此而已),则使用JsonProperty属性(不需要的地方)将默认解析器指定为json中的字段名。
我希望你的麻烦解决了,请下次多读些文件,在研究中要更有耐心。

相关问题