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