David
David

Reputation: 16028

Serialize and ignore properties which throw an exception

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

Answers (3)

David
David

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

nomail
nomail

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

TJHeuvel
TJHeuvel

Reputation: 12608

You could use an external JSON serialization library such as this one and add a custom attribute to skip the value. Or perhaps add a try catch around getting the value and ignoring it when the trap is sprung.

Upvotes: 0

Related Questions