1. 程式人生 > 實用技巧 >newtonsoft.json的大小駝峰及蛇形命名法轉換實現跨平臺溝通

newtonsoft.json的大小駝峰及蛇形命名法轉換實現跨平臺溝通

C#的屬性是大駝峰命名法,python欄位是蛇形命名法,C++是小駝峰命名法,C++和python無法反序列化C#序列化得到的Json字串。
newtonsoft.json功能很強大,他能在序列化或反序列時,自動實現三種命名法的轉換。

class MessageBody
{
    public int MyIDNum { get; set; }
    public bool IsCheck { get; set; }
}

序列化時,採用大駝峰,小駝峰,還是蛇形命名法隨意選擇

MessageBody msg = new MessageBody() { MyIDNum = 1, IsCheck = false };

string json = JsonConvert.SerializeObject(msg,Formatting.Indented);
Console.WriteLine(json);

json = JsonConvert.SerializeObject(msg,Formatting.Indented,new JsonSerializerSettings()
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Console.WriteLine(json);

json = JsonConvert.SerializeObject(new MessageBody() { MyIDNum = 1, IsCheck = false }, Formatting.Indented, new JsonSerializerSettings()
{
    ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() }
});
Console.WriteLine(json);
//{
//  "MyIDNum": 1,
//  "IsCheck": false
//}
//{
//  "myIDNum": 1,
//  "isCheck": false
//}
//{
//  "my_id_num": 1,
//  "is_check": false
//}

反序列化時,可以把蛇形的Json字串反序列成大駝峰命名法的.NET物件

MessageBody body = JsonConvert.DeserializeObject<MessageBody>("{'my_id_num':1,'is_check':false}", new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() } });
Console.WriteLine(body.MyIDNum);
Console.WriteLine(body.IsCheck);
//1
//False