Search code examples
c#asp.netjson.netdeserializationanonymous-methods

Deserializing json issue - inherited linq2SQL object


I have used Linq-to-SQL objects in my web app. My base and inherited classes look like this:

//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; }

}

when serialize, the Json OUTPUT is (note the ActiveAdsCount and DisplaySequence values):

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

When I am calling the deserialze object method

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

where T is List Result: it shows "ActiveAdsCount" and "DisplaySequence" have 0 values while the json shows proper correct information coming from Database. So, the problem is in deserialization.

I am using 4.5.1 version of Newtonsoft.Json.dll of .Net 4.0 framework


Solution

  • Moreover, I have marked my CategoryEntity class with DataContract attribute and its members to Datamember for serialization purpose. I notice that the Serialization attribute is making only the instance as serializable but not its members. So, the new class look like this:

    [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 Thanks very much for your comment.