mercredi 26 avril 2017

Instantiate an instance of a Type including all object properties and adhere to inheritance

I'm not sure if that title is reflective of the actual question, so let me explain. Is there a way to instantiate a class and recursively instantiate all properties that are classes?

For example :

public class Base
{
    public int BaseValue{ get; set;} 
}

public class Extended : Base
{
    public int ExtendedValue{ get; set;}
    public AnotherExtendedClass AnotherClass { get; set;}
}

I would like to create a json payload comprised of an empty instance of Extended with all default values and properties instantiated. And use it like:

string representation = Test.CreateDefaultEmptyJson(Extended);

public static string CreateDefaultEmptyJson(Type type)
{
    JsonSerializerSettings settings = new JsonSerializerSettings().Configure();
    var defaultInstance= Activator.CreateInstance(type);
    return JsonConvert.SerializeObject(defaultInstance, settings);
}

The output does not include the Extended class properties. I get back :

{
    "BaseValue":0
}

When I would really like to see ( or something similar ):

{
    "BaseValue":0,
    {
         "ExtendedValue":0,
         {
             ...
         }
    }
}

I suppose I could recursively iterate all types of Extended and call the default constructor, however, before I go down that road there may be a few lines of code to accomplish the same.





Aucun commentaire:

Enregistrer un commentaire