首页 文章

如何获取JSON序列化的阴影属性而不是基本属性?

提问于
浏览
1

在我的ASP.NET MVC Web应用程序中,我使用内置的 Controller.Json() 方法来序列化对象并将其发送回客户端以响应AJAX调用 . 被序列化的对象的类继承自具有一些共享属性名称的另一个类 . 这是故意的,因为我需要属性名称来匹配一些反射's happening. I am 692023 those properties in the derived class so that they can be a different type from their same-name counterpart in the base class. Here'是一个简化的例子:

public class BaseModel
{
    public string Title { get; set; }
    public decimal CleanUpHours { get; set; }
    public decimal InstallHours { get; set; }
}

public class DerivedModel : BaseModel
{
    public new BucketHoursWithCalculations CleanUpHours { get; set; }
    public new BucketHoursWithCalculations InstallHours { get; set; }
}

当我序列化 DerivedModel 的实例时,客户端上的JSON对象仅包含 CleanUpHoursInstallHoursdecimal 版本,而不是我的自定义类 BucketHoursWithCalculations .

在序列化之前检查Visual Studio中的对象会显示这些属性的基本和派生版本,如此处所示(请原谅所有额外属性 - 上面的示例类比我实际使用的更简单,但原理是一样的):

Visual Studio

这是在客户端序列化为JSON后,该对象在客户端上的样子:

ng-inspector in Chrome

如您所见,派生/阴影属性未被序列化,并且基本属性是,但仅在存在名称冲突的情况下(例如,基本模型中的 Title 属性序列化很好) .

我如何仅序列化阴影属性,其中's a name conflict? I don' t相信在基础属性上更改访问修饰符(即从 publicprotected 或其他东西)将适用于我的情况,因为 BaseModel 由实体框架使用,并且必须具有公共属性 . 任何帮助,将不胜感激 .

1 回答

  • 3

    一种想法是在基础模型上定义用于hours属性的类型参数 . 然后,为 decimalBucketHoursWithCalculations 定义派生模型 . 我很想知道 BucketHoursWithCalculations 如何序列化为JSON,但无论如何应该序列化 CleanUpHoursInstallHours 属性 .

    // use a type parameter on the base model that must be specified
    // in derived models.
    public class BaseModel<THours>
    {
        public string Title { get; set; }
        public THours CleanUpHours { get; set; }
        public THours InstallHours { get; set; }
    }
    
    // hours are specified as decimals
    public class DecimalModel : BaseModel<decimal>
    {
    }
    
    // hours are specified as BucketHoursWithCalculations    
    public class BucketHoursWithCalculationsModel : BaseModel<BucketHoursWithCalculations>
    {
    }
    
    // usage
    DecimalModel d = new DecimalModel();
    d.CleanUpHours = 1.0M; // CleanUpHours is a decimal here
    
    BucketHoursWithCalculationsModel b = new BucketHoursWithCalculationsModel();
    b.CleanUpHours = new BucketHoursWithCalculations();
    b.CleanUpHours.SomeProperty = 1.0M;
    

相关问题