I have an object which contains a list of additional information.
public class ParentObject
{
public string Prop1{ get; set; }
public string Prop2{ get; set; }
public IList<BaseInformation> AdditionalInformation{get;set;}
}
public abstract class AbstractInformation {}
public class ConcreteInformation1 : AbstractInformation
{
public string Concrete1Extra1{ get; set; }
public string Concrete1Extra2{ get; set; }
}
public class ConcreteInformation2 : AbstractInformation
{
public string Concrete2Extra1{ get; set; }
}
I want to have an json object like this
{
"Prop1": "MyValue1", //From ParentObject
"Prop2": "MyValue2", //From ParentObject
"Concrete1Extra1" : "Extra1" // From ConcreteInformation1
"Concrete1Extra2" : "Extra2" // From ConcreteInformation1
"Concrete2Extra1" : "Extra3" // From ConcreteInformation2
}
I know my goal looks very error prone (Having two ConcreteInformation1 objects in the list will cause duplicate property names) but I simpified my question and example in order to focus only on finding a solution for combining the list as properties into the parent object.
I have tried to write my own JsonConverter but that's giving an error on o.AddBeforeSelf()
because the JObject.Parent is null.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
o.AddBeforeSelf(new JProperty("PropertyOnParent", "Just a test"));
o.WriteTo(writer);
}
}