C# JsonConvert 字段映射处理方法

C# Newtonsoft.Json.JsonConvert可以进行序列化处理,有时序列化存在特殊字段,可以通过JsonProperty来处理。

Json格式:

{
  "appName":"PascalMingService",
  "Timestamp":"2021-07-12 18:47:55.156",
  "os.name":"Linux",
  "os.arch":"amd64"
}

数据类定义如下:

class InfoData
{
     public String appName;
     public String Timestamp;
     [JsonProperty(PropertyName = "os.name")]
     public String osname;
     [JsonProperty(PropertyName = "os.arch")]
     public String osarch;
}

验证代码:

public void testInfo()
{ 
   String infoStr = "{ \"appName\":\"PascalMingService\",\"Timestamp\":\"2021-07-12 18:47:55.156\",\"os.name\":\"Linux\",\"os.arch\":\"amd64\"}";
   InfoData info = JsonConvert.DeserializeObject(infoStr);
   Console.WriteLine($"InfoData appName:{info.appName},Timestamp:{info.Timestamp},os.name:{info.osname},os.arch:{info.osarch}");
}

输出:

 

你可能感兴趣的:(编程,c#,json,.net)