Newtonsoft是我們開發程序中經常用到的一個第三方類別庫,主要用于物件的序列化和反序列化,
命名方式
默認情況下序列化后的json字串會以類名、屬性名作為鍵來命名,問題在于C#的命名規范中類名、屬性名都是以PascalCase方式來命名的,而在前端中一般都是以CamelCase方式來命名的,所以我們可以通過Newtonsoft提供的一些方法來滿足我們所需的效果,直接看示例:
public class Book { public string BookName { get; set; } public decimal BookPrice { get; set; } public string AuthorName { get; set; } public int AuthorAge { get; set; } public string AuthorCountry { get; set; } }
Book book = new Book { BookName = "The Gathering Storm", BookPrice = 16.19m, AuthorName = "Brandon Sanderson", AuthorAge = 34, AuthorCountry = "United States of America" }; string json1 = JsonConvert.SerializeObject(book, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver() }); //首字母大寫,PascalCase方式 //{ // "BookName": "The Gathering Storm", // "BookPrice": 16.19, // "AuthorName": "Brandon Sanderson", // "AuthorAge": 34, // "AuthorCountry": "United States of America" //} string json2 = JsonConvert.SerializeObject(book, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); //首字母小寫,CamelCase方式 //{ // "bookName": "The Gathering Storm", // "bookPrice": 16.19, // "authorName": "Brandon Sanderson", // "authorAge": 34, // "authorCountry": "United States of America" //}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/103525.html
標籤:C#
上一篇:C#中獲取指定路徑下指定后綴名的所有檔案的路徑的list
下一篇:C#函式(建構式)的多載
