Reputation: 16028
Say I have a class:
public class Cat
{
public int Hunger {get; set;}
public int Sleepiness {get; set;}
public int Usefullness {
get { throw new DivideByZeroException(); }
}
}
Is it possible to serialize it as below:
public ActionResult GetMyCat()
{
Cat c = new Cat()
{
Hunger = 10,
Sleepiness = 10
};
return Json(c);
}
I can't modify the "Cat" class. Can I have the MVC JSON Serializer ignore the error that one property threw, (if it threw an error) and just give me an empty/default value for that property?
Upvotes: 3
Views: 997
Reputation: 16028
Ok, This is ugly, but here is one way:
Cat c = new Cat()
{
Hunger = 10,
Sleepiness = 10
};
dynamic dynamicCat = new ExpandoObject();
IDictionary<string, object> dynamicCatExpando = dynamicCat;
Type type = c.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
try
{
dynamicCatExpando.Add(property.Name, property.GetValue(c, null));
}
catch (Exception)
{
//Or just don't add the property here. Your call.
object defaultValue = type.IsValueType ? Activator.CreateInstance(type) : null;
dynamicCatExpando.Add(property.Name, defaultValue); //I still need to figure out how to get the default value if it's a primitive type.
}
}
return Content(JsonConvert.SerializeObject(dynamicCatExpando), "application/Json");
Upvotes: 1
Reputation: 650
Create class extension that will return proper object
public static class CatExtensions
{
public static object GetObject(this Cat value)
{
return new
{
Hunger = value.Hunger,
Sleepiness = value.Sleepiness
}
}
}
Upvotes: 2