I'm using json.net to serialize my responses to the client I'm building a controller action (in mvc) that produce a json string from types of objects
so it looks something like this:
string json = JsonConvert.SerializeObject(Activator.CreateInstance(type));
my problem is that when an object has an object inside of it (complex type), the activator assign null to it and then, the Json serializer doesn't serialize it at all
for example
if my object class looks like this:
public class Phone
{
public string Name {get; set;}
public Model Model {get; set;}
}
public class Model
{
public string Name {get; set;}
public string IMEI {get; set;}
}
the json string will be:
{"Name":null, "Model":null}
so is there a way to make be:
{"Name":null, "Model":{"Name":null, "IMEI":null}}
thank you all for your answers
OK
it took me some time to write this answer (stack overflow restriction) but i've found a great way to do it with reflection and recurssion
I've created this method:
public void CreateFullInstance(object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach(var property in properties)
{
Type propertyType = property.PropertyType;
if(!propertyType.IsPrimitive &&
propertyType.GetConstructor(Type.EmptyTypes) != null)
{
var val = Activator.CreateInstance(propertyType);
property.SetValue(obj,val);
CreateFullInstance(val);
}
}
}
when I call it, I just pass my initial:
var phone = Activator.CreateInstance(propertyType);
CreateFullInstance(phone);
var json = JsonConvert.SerializeObject(phone);
the downside for this method is that objects with no empty constructor will be ignored. I think I can fix that but then again as I said, these are POCO models so they all have empty constructors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With