序列化并忽略引发异常的属性

本文关键字:异常 属性 序列化 | 更新日期: 2023-09-27 18:15:59

假设我有一个类:

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序列化器忽略一个属性抛出的错误,(如果它抛出了一个错误),只是给我一个空/默认值的属性?

序列化并忽略引发异常的属性

创建将返回适当对象的类扩展

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

好吧,这是丑陋的,但这里有一个方法:

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

您可以使用外部JSON序列化库,例如这个库,并添加一个自定义属性来跳过该值。或者添加一个try catch来获取该值,并在触发陷阱时忽略它。