环境:
- .net 6.0
- vs2022
系列篇:
《c#:System.Text.Json 的使用一》
《c#:System.Text.Json 的使用二》
《c#:System.Text.Json 的使用三(从Newtonsoft迁移)》
《c#:System.Text.Json 的使用四(如何忽略[JsonPropertyName])》
参考:
《C# 序列化Json时如何忽略JsonProperty(PropertyName =" someName")》
《自定义 JSON 协定》
1. System.Text.Json
csharp
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Reflection;
//默认输出: {"kname":"jack"}
//var jsonDefault = JsonSerializer.Serialize(new Person { Name = "jack" });
//使用 Modifiers 达到期望, 输出: {"Name":"jack"}
var json = JsonSerializer.Serialize(new Person { Name = "jack" }, new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers = { (typeInfo) =>
{
for (int i = 0; i < typeInfo.Properties.Count; i++)
{
var property = typeInfo.Properties[i];
var prop = property.AttributeProvider as PropertyInfo;
if (prop != null) property.Name = prop.Name;
}
}
}
}
});
public class Person
{
[JsonPropertyName("kname")]
public string Name { get; set; }
}
2. NewtonSoft
csharp
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
//默认输出: {"kname":"jack"}
//var jsonDefault = JsonConvert.SerializeObject(new Person { Name = "jack" });
//使用 ContractResolver 达到期望, 输出: {"Name":"jack"}
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LongNameContractResolver();
var json = JsonConvert.SerializeObject(new Person { Name = "jack" }, settings);
public class Person
{
[JsonProperty("kname")]
public string Name { get; set; }
}
public class LongNameContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);
foreach (JsonProperty prop in list)
{
prop.PropertyName = prop.UnderlyingName;
}
return list;
}
}