Reputation: 2032
I'm attempting to serialize a class hierarchy in Newtonsoft Json using C#.
My class structure looks like this:
public abstract class Foo
{
public string PropertyOne{get;set;}
}
public class Bar : Foo
{
public string PropertyTwo{get; set;}
}
When I serialize my Bar class I have only the PropertyOne property from the Foo class not the PropertyTwo from the Bar Class. The properties of the abstract base class are common to the majority of our messages so having a hierarchy feels like the best practice option.
Does anyone know how to get the serialized to include all atributes from the base class as well as the subclass, without removing the hierarchy?
Upvotes: 1
Views: 1976
Reputation: 624
I had this problem because my main class had DataContract serialisation (DataMember) and my parent class did not.
Posted as prompter for a stupid error :-)
Upvotes: 1
Reputation: 9098
JsonConvert.SerializeObject
seems to do the trick for me
string json = JsonConvert.SerializeObject(new Bar{ PropertyOne = "hello", PropertyTwo = "world" });
Output:
{"PropertyTwo":"world","PropertyOne":"hello"}
Upvotes: 1