序列化并忽略抛出异常的属性

时间:2015-10-05 12:45:50

标签: c# json asp.net-mvc

说我有课:

public class Cat
{
    public int Hunger {get; set;}
    public int Sleepiness {get; set;}
    public int Usefullness {
      get { throw new DivideByZeroException(); }
    }
}

是否可以按如下方式对其进行序列化:

public ActionResult GetMyCat()
{
     Cat c = new Cat()
    {
        Hunger = 10,
        Sleepiness = 10
    };

    return Json(c);
}

我无法修改“Cat”类。我可以让MVC JSON Serializer忽略一个属性抛出的错误(如果它抛出错误)并且只给我一个该属性的空/默认值吗?

3 个答案:

答案 0 :(得分:2)

创建将返回正确对象的类扩展

public static class CatExtensions
 {
        public static object GetObject(this Cat value)
        {
            return new
            {
                Hunger = value.Hunger,
                Sleepiness = value.Sleepiness
            }
        }
    }

答案 1 :(得分:1)

好的,这很难看,但这是一种方式:

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");

答案 2 :(得分:0)

您可以使用外部JSON序列化库(例如this one)并添加自定义属性以跳过该值。或者也许添加一个try catch来获取值并在陷阱出现时忽略它。