是的,您可以创建自定义合同解析器并自JsonProperty
定义定义,而无需使用属性。示例如下:
class Person { public string First { get; set; } }
class PersonContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(
MemberInfo member,
MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (member.DeclaringType == typeof(Person) && member.Name == "First")
{
property.PropertyName = "FirstName";
}
return property;
}
}
class Program
{
static void Main(string[] args)
{
var result = JsonConvert.SerializeObject(
new Person { First = "John" },
new JsonSerializerSettings
{
ContractResolver = new PersonContractResolver()
});
Console.WriteLine(result);
}
}
此示例程序的输出如下:
// {"FirstName":"John"}