C#

Json.NET(Newtonsoft.Json.dll) - 2.序列化时,key为小驼峰式

文章目录
  1. 1. ♠ 驼峰式
  2. 2. ♠ 全局设置
  3. 3. ♠ 局部使用

驼峰式

驼峰式:是变量命名时的一种常用方式。

命名原因:

  • 因其命名样式类似驼峰而得名。
  • 来自 Perl 语言中普遍使用的大小写混合格式,而 Larry Wall 等人所著的畅销书《Programming Perl》(O’Reilly 出版)的封面图片正是一匹骆驼。

例如:我的名字(myname),驼峰式命名为MyName或myName。

驼峰式(camel case)分为大驼峰式(upper camel case)和小驼峰式(lower camel case)。
其中,MyName为大驼峰式,myName为小驼峰式。

全局设置

所有的序列化操作key值都设为小驼峰式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
//设置全局
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
json = JsonConvert.SerializeObject(product);
//{
// "name": "Widget",
// "expiryDate": "2010-12-20T18:01:00Z",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}

局部使用

当前的序列化操作key值都设为小驼峰式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "2010-12-20T18:01:00Z",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}

(幽蛰 写于 2018.01.10)