我正在使用.NET WebAPI来构建自定义API。我要做的是在运行时动态更改属性datamember名称。我知道我可以通过使用DataMember(Name =“whateverId”)来覆盖名称,但我希望能够动态地更改它。
请参阅下面的示例。该类具有id和name字段。有时我可能希望它显示为“eventId”和“name”。其他时候我可能希望它是“subEventId”和“name”。
任何想法如何动态地执行此操作。
[DataContract(Namespace = "", Name = "pair")]
public class idName
{
[DataMember(EmitDefaultValue = false]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? id { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string name { get; set; }
public idName()
{
}
public idName(int? id, string name, string serializeIdName = "id")
{
this.id = id;
this.name = name;
}
}
我可以在代码中创建一个新的datamemberattribute但我不知道接下来该怎么做。
var dma = new DataMemberAttribute();
dma.Name = "whateverId";
谢谢!
答案 0 :(得分:0)
您可以使用序列化回调,如下所示:
[DataContract]
public class IdName
{
public int? Id { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
private string EventId { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
private string SubEventId { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Name { get; set; }
[OnSerializing]
void OnSerializing(StreamingContext context)
{
bool isEvent = true;
if (isEvent)
{
this.EventId = this.Id.ToString();
}
else
{
this.SubEventId = this.Id.ToString();
}
}
}
答案 1 :(得分:0)
这是我不太理想但改进的方法。
public class idName
{
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? id { get; set; }
#region Alternate id names
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? eventId { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? subEventId { get; set; }
//as many other id's as needed.
#endregion
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string name { get; set; }
public idName() { }
public idName(int? id, string name, string displayIdName = "id")
{
this.name = name;
PropertyInfo prop = this.GetType().GetProperty(displayIdName);
if (prop == null)
this.id = id;
else
prop.SetValue(this, id);
}
}