使用Newtonsoft序列化

Newtonsoft是咱们开发过程当中常常用到的一个第三方类库,主要用于对象的序列化和反序列化。前端

 

命名方式json

默认状况下序列化后的json字符串会以类名、属性名做为键来命名。问题在于C#的命名规范中类名、属性名都是以PascalCase方式来命名的,而在前端中通常都是以CamelCase方式来命名的,因此咱们能够经过Newtonsoft提供的一些方法来知足咱们所需的效果,直接看示例: spa

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"
//}
相关文章
相关标签/搜索