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" //}
如对本文有疑问, 点击进行留言回复!!
C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)
Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)
网友评论