我想在一个单独的文件中找到我的JsonSerializer设置,该文件与主类文件一起形成一个分部类。可以使用MetadataTypeAttribute
:
[MetadataType(typeof(MyMeta))]
public partial class MainClass
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
internal sealed class MyMeta
{
[JsonIgnore]
public int ID { get; set; }
[JsonProperty(PropertyName = "Title")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Functions")]
[JsonConverter(typeof(MyConverter))]
public string Description { get; set; }
}
但如果无法将MetadataTypeAttribute
附加到MainClass
怎么办?我尝试在我的Web API控制器中使用派生类:
public partial class MainClass
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
[MetadataType(typeof(MyMeta))]
public partial class HelperClass : MainClass
{ }
public class TestController : ApiController
{
public IEnumerable<HelperClass> Get()
{
var list = new List<HelperClass>()
{
new HelperClass() { ID = 0, Name = "Title 0", Description = "Description 0"},
new HelperClass() { ID = 1, Name = "Title 1", Description = "Description 1"},
new HelperClass() { ID = 2, Name = "Title 2", Description = "Description 2"}
};
return list;
}
}
这个技巧works fine用于验证属性,但不影响TestController
结果。为什么?
如何在不覆盖/遮蔽/封装其公共属性的情况下将特定的JsonSerializer设置应用于MainClass
的实例?