C# 如何为父类设置JSON属性
我有: TableEntity是外部库的一部分,我无法向其添加属性 我想将PartitionKey和RowKey的JsonProperty设置为:“GroupID”和“ItemID”,部分是为了隐藏通过JSON公开的实现C# 如何为父类设置JSON属性,c#,json,asp.net-web-api,json.net,C#,Json,Asp.net Web Api,Json.net,我有: TableEntity是外部库的一部分,我无法向其添加属性 我想将PartitionKey和RowKey的JsonProperty设置为:“GroupID”和“ItemID”,部分是为了隐藏通过JSON公开的实现 我该怎么做 一般来说,将实体转换为适当的视图模型更容易(我几乎从不将原始实体传递给JSON/视图)。如果此示例只是对象的一部分,并且实际上有一些属性可以将名称与VM定义相匹配,那么可以使用AutoMapper使填充VM更容易。如果所有属性都不匹配,那么只需给VM一个构造函数,该
我该怎么做 一般来说,将实体转换为适当的视图模型更容易(我几乎从不将原始实体传递给JSON/视图)。如果此示例只是对象的一部分,并且实际上有一些属性可以将名称与VM定义相匹配,那么可以使用AutoMapper使填充VM更容易。如果所有属性都不匹配,那么只需给VM一个构造函数,该构造函数接受您的实体并为其属性赋值,实际上就更容易了
class TableEntity
{
public string PartitionKey {get; set;}
public string RowKey {get; set;}
}
class MyEntity : TableEntity
{
[JsonProperty(PropertyName = "myAFieldName")]
public string AField {get; set;}
}
您是否尝试使用
MetadataTypeAttribute
()
另请参见:问题完全不同(我试图重命名通过继承引入的字段,而不是隐藏我正在序列化的第三方类的字段)。但是,是的,似乎同样的解决方案也适用。我将在下面对这两个答案进行投票,因为它们都是解决方案。但最终,我想我会同意另一个问题的解决方案:
public class MyEntityVM
{
public MyEntityVM(MyEntity entity)
{
this.ItemId = entity.RowKey;
//etc...
}
public string ItemId {get;set;}
public string GroupId {get;set;}
public string MyAFieldName {get;set;
}
class TableEntity
{
public string PartitionKey {get; set;}
public string RowKey {get; set;}
}
[MetadataType(typeof(MyEntityMeta))]
class MyEntity : TableEntity
{
public string AField {get; set;}
}
public class MyEntityMeta
{
[JsonProperty(PropertyName = "GroupID")]
public string PartitionKey {get; set;}
[JsonProperty(PropertyName = "myAFieldName")]
public string AField {get; set;}
}