您必须重写
DefaultContractResolver并实现自己的机制来提供
PropertyName(以JSON格式)。我将提供完整的示例代码,以显示生成的运行时的反序列化和序列化
PropertyName。当前,它将
Test字段修改为
Test5(在所有模型中)。您应该实现自己的机制(使用属性,保留名称,表等)。
class Program{ static void Main(string[] args) { var customer = new Customer() {Email = "asd@asd.com", Test = "asdasd"}; var a = Serialize(customer, false); var b = Serialize(customer, true); Console.WriteLine(a); Console.WriteLine(b); var desA = Deserialize<Customer>(a, false); var desB = Deserialize<Customer>(b, true); Console.WriteLine("TestA: {0}", desA.Test); Console.WriteLine("TestB: {0}", desB.Test); } static string Serialize(object obj, bool newNames) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Formatting = Formatting.Indented; if (newNames) { settings.ContractResolver = new CustomNamesContractResolver(); } return JsonConvert.SerializeObject(obj, settings); } static T Deserialize<T>(string text, bool newNames) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Formatting = Formatting.Indented; if (newNames) { settings.ContractResolver = new CustomNamesContractResolver(); } return JsonConvert.DeserializeObject<T>(text, settings); }}class CustomNamesContractResolver : DefaultContractResolver{ protected override IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization) { // Let the base class create all the JsonProperties // using the short names IList<JsonProperty> list = base.CreateProperties(type, memberSerialization); // Now inspect each property and replace the // short name with the real property name foreach (JsonProperty prop in list) { if (prop.UnderlyingName == "Test") //change this to your implementation! prop.PropertyName = "Test" + 5; } return list; }}public class Customer{ [JsonProperty(PropertyName = "email")] public string Email { get; set; } public string Test { get; set; }}输出:
{ "email": "asd@asd.com", "Test": "asdasd"}{ "email": "asd@asd.com", "Test5": "asdasd"}TestA: asdasdTestB: asdasd如您所见,按预期,当我们使用
Serialize(..., false)-字段名称为时,
Test以及当我们使用
Serialize(...,true)-字段名称
Test5为时。这也适用于反序列化。



