【问题标题】:Deserializing json issue - inherited linq2SQL object反序列化 json 问题 - 继承的 linq2SQL 对象
【发布时间】:2012-03-25 10:15:28
【问题描述】:

我在我的网络应用程序中使用了 Linq-to-SQL 对象。我的基类和继承类如下所示:

//Base Class: this will define the attributes that is auto-generated
//when using Linq-2-SQL ORM. Note this class is a partial class
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Categories")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged 


//Inherited Class:
[Serializable]
public class CategoryEntity : Category
{
    private int _ActiveAdsCount;

    public int ActiveAdsCount
    {
        get
        {
            return _ActiveAdsCount;
        }

        set
        {
            _ActiveAdsCount = value;
        }
    }

    public int DisplaySequence { get; set; }

}

序列化时,Json OUTPUT 为(注意 ActiveAdsCount 和 DisplaySequence 值):

[{"ActiveAdsCount":3429,"DisplaySequence":99,"CategoryID":636,"ParentCategoryID":635,"CategoryName":"propForRent","CategoryImageFN":null}]

当我调用反序列化对象方法时

result = JsonConvert.DeserializeObject<T>(responseText);

其中 T 是列表 结果:它显示“ActiveAdsCount”和“DisplaySequence”的值为 0,而 json 显示来自数据库的正确信息。所以,问题在于反序列化。

我使用的是.Net 4.0框架的Newtonsoft.Json.dll 4.5.1版本

【问题讨论】:

  • 看看这里发布的类似问题:stackoverflow.com/questions/7987302/…
  • @JasonJong 感谢您的链接。我现在就试试!
  • 是的,它就像一个魅力 :) @JasonJong 非常感谢朋友,上帝保佑

标签: c# asp.net json.net deserialization anonymous-methods


【解决方案1】:

此外,我已将我的 CategoryEntity 类标记为 DataContract 属性,并将其成员标记为 Datamember 以进行序列化。我注意到 Serialization 属性仅使实例可序列化,而不是其成员。因此,新类如下所示:

[DataContract]
public class CategoryEntity : Category
{
    [DataMember]
    public int ActiveAdsCount { get; set; }

    [DataMember]
    public int DisplaySequence { get; set; }

    [DataMember]
    public IList<CategoryEntity> SubCategories { get; set; }

    [DataMember]
    public IList<BasicCategoryInfo> SubCategoriesBasicInfoList { get; set; }

    [DataMember]
    public string ParentCategoryNameEn { get; set; }

    [DataMember]
    public int CityID { get; set; }
}

@JasonJong 非常感谢您的评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多