Serializing Derived Type Properties from Base Type Collection Using NewtonSoft Json.NET

Update: Allowed! Json.NET seems to include properties of the derived type by default, but they were not included due to a bug in my code where the derived type was overwritten by the base type.


I am currently working on a project for a school and I stumbled upon a problem.

I need to serialize a Json object that I am using with Newtonsoft Json.NET. The object I am trying to serialize has a list of objects of a specific base class, but the objects in that list have derived types with their own unique properties.

Currently, only base class properties are included in the resulting Json. If possible, I would like the Json converter to detect which derived class is an object in the collection and serialize their unique properties.

Below is some code as an example of what I am doing.

The classes I am using:

public class WrappingClass
{
    public string Name { get; set; }
    public List<BaseClass> MyCollection { get; set; }
}

public class BaseClass
{
    public string MyProperty { get; set; }
}

public class DerivedClassA : BaseClass
{
    public string AnotherPropertyA { get; set; }
}

public class DerivedClassB : BaseClass
{
    public string AnotherPropertyB { get; set; }
}

      

Serializing some mock objects:

WrappingClass wrapperObject = new WrappingClass
{
    Name = "Test name",
    MyCollection = new List<BaseClass>();
};

DerivedClassA derivedObjectA = new DerivedClassA
{
    MyProperty = "Test my MyProperty A"
    AnotherPropertyA = "Test AnotherPropertyA"
};

DerivedClassB derivedObjectB = new DerivedClassB
{
    MyProperty = "Test my MyProperty B"
    AnotherPropertyB = "Test AnotherPropertyB"
};

wrapperObject.MyCollection.Add(derivedObjectA);
wrapperObject.MyCollection.Add(derivedObjectB);

var myJson = JsonConvert.SerializeObject(wrapperObject);

      

Json that will currently be generated:

{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A"}{"MyProperty":"Test my MyProperty B"}]}

      

Json I want:

{"Name":"Test name","MyCollection":[{"MyProperty":"Test my MyProperty A","AnotherPropertyA":"Test AnotherPropertyA"},{"MyProperty":"Test my MyProperty B","AnotherPropertyB":"Test AnotherPropertyB"}]}

      

Any ideas? Thank!

+3


source to share


2 answers


The default json.NET behavior is to include all properties in derived types. The only reason you won't get them is if you have defined [DataContract]

in a base type that you have not propagated to your derived types, or if you have something like optin serialization ect.



+2


source


Decorate the properties with the Ignore attribute if you don't want them to be serialized like



public class DerivedClassA : BaseClass
{
    [JsonIgnore]
    public string AnotherPropertyA { get; set; }
}
      

Run codeHide result


-1


source







All Articles