我有一堂课,有以下领域。这些属性用于在需要调用外部rest API方法时序列化为json对象。
public class Customer { [JsonProperty(PropertyName = "email")] public string Email { get; set; } [JsonProperty(PropertyName = "prop[listId]")] public string Test{ get; set; } // there are lot of properties }
在属性名称中Test,外部API服务调用需要一些类似json归档名称格式的内容。
Test
prop[7]
就我而言,这7可以根据诸如test,dev和prod之类的环境进行更改。因此,我正在寻找一种将listId值移动到app.config中的方法。
7
我尝试按照以下方式进行操作,但不允许这样做。listIdValue如果分配常数值,它将起作用。
listIdValue
private string listIdValue = ConfigurationManager.AppSettings["ListIdValue"]; [JsonProperty(PropertyName = "prop["+listIdValue +"]")] public string Test{ get; set; }
您必须重写DefaultContractResolver并实现自己的机制来提供PropertyName(以JSON格式)。我将提供完整的示例代码,以显示生成的运行时的反序列化和序列化PropertyName。当前,它将Test字段修改为Test5(在所有模型中)。您应该实现自己的机制(使用属性,保留名称,表等)。
DefaultContractResolver
PropertyName
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: asdasd TestB: asdasd
如您所见,按预期,当我们使用Serialize(..., false)-字段名称为时,Test以及当我们使用Serialize(..., true)-字段名称Test5为时。这也适用于反序列化。
Serialize(..., false)
Serialize(..., true)