.getJson调用不使用继承的对象

时间:2013-04-09 20:12:59

标签: c# jquery json inheritance serialization

第一篇文章...通常我能够搜索并找到问题的答案,但这次我无法做到。我有一个使用大量其他对象的对象:

[DataContract]
public class CoolStuff
{
    [DataMember]
    public Field[] CoolField { get; set; }

    public CoolStuff()
    {
        CoolField = SetCoolField();
    }

    private Field[] SetCoolField()
    {
        return new Field[]
        {
            new Field("Project Information", "ProjectInformation"),
            new Field("Resource Information", "ResourceInformation"),
        }
     }
}

[DataContract]
public class Field
{
    [DataMember]
    public string Prompt { get; set; }
    [DataMember]
    public string Value { get; set; }
    [DataMember]
    public bool IsLocked { get; set; }

    public Field(string prompt, string value = "n/a", bool isLocked = false)
    {
        Prompt = prompt;
        Value = value;
        IsLocked = isLocked;
    }
}

我从一个服务调用我的构造函数,当我尝试使用$ .getJSON(/Service.svc/coolstuff/'+ id,loadCoolStuff)序列化它时,这很好用,花花公子;

问题是,当我让我的Field类从另一个类继承时,.getJson调用失败而没有给我一个理由。

[DataContract]
public class CoolStuff
{
    [DataMember]
    public FieldBase[] CoolField { get; set; }

    public CoolStuff()
    {
        CoolField = SetCoolField();
    }

    private FieldBase[] SetCoolField()
    {
        return new FieldBase[]
        {
            new Field("Project Information", "ProjectInformation"),
            new Field("Resource Information", "ResourceInformation"),
        }
    }
}

[DataContract]
public class FieldBase
{

}

[DataContract]
public class Field : FieldBase
{
    [DataMember]
    public string Prompt { get; set; }
    [DataMember]
    public string Value { get; set; }
    [DataMember]
    public bool IsLocked { get; set; }

    public Field(string prompt, string value = "n/a", bool isLocked = false)
    {
        Prompt = prompt;
        Value = value;
        IsLocked = isLocked;
    }
}

有人可以解释为什么用这个代码,我对.getJSON的调用失败了吗?我真的被困在这里了。非常感谢!

1 个答案:

答案 0 :(得分:0)

好的,在我推断出您正在使用WCF进行此Web服务的行之间进行阅读。使用{。1}}属性和以.svc结尾的url使其足够清晰。这是相关的,因为这个问题似乎与WCF序列化的方式有关。正如我在上面的注释中所提到的,使用默认的Newtonsoft JSON序列化程序,ASP.NET Web API中的相同类结构存在 no 问题。

这里需要的是DataContract属性,以正确定义序列化的派生类型。

This article提供了一些直截了当的例子。 This one有更多关于概念的详细信息。

对于您提供的示例,您需要像这样装饰FieldBase定义:

KnownType

请注意,这会为您的JSON添加额外字段,例如[DataContract] [KnownType(typeof(Field))] public class FieldBase { } 。你可以忽略它,或者如果困扰你就去寻找摆脱它的方法。我不保证这是可能的。