我有一门课,有以下领域。这些属性用于在需要调用外部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归档名称格式的内容。
prop[7]
就我而言,这7
可以根据test,dev和prod等环境进行更改。因此,我正在寻找一种将listId值移动到app.config中的方法。
我尝试按照以下方式进行操作,但不允许这样做。listIdValue
如果分配常数值,它将起作用。
private string listIdValue = ConfigurationManager.AppSettings["ListIdValue"];
[JsonProperty(PropertyName = "prop["+listIdValue +"]")]
public string Test{ get; set; }
您将必须重写DefaultContractResolver
并实现自己的机制来提供PropertyName
(以JSON格式)。我将提供完整的示例代码来显示反序列化和序列化以及生成的运行时PropertyName
。当前,它将Test
字段修改为Test5
(在所有模型中)。您应该实现自己的机制(使用属性,保留名称,表等)。
class Program
{
static void Main(string[] args)
{
var customer = new Customer() {Email = "[email protected]", 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": "[email protected]",
"Test": "asdasd"
}
{
"email": "[email protected]",
"Test5": "asdasd"
}
TestA: asdasd
TestB: asdasd
如您所见,当我们使用Serialize(..., false)
-字段名称为时,Test
和我们使用Serialize(..., true)
-字段名称为时Test5
,正如预期的那样。这也适用于反序列化。
我已将此答案用作回答的错误:https ://stackoverflow.com/a/20639697/773879
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句