假设我有一个类:
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 忽略一个属性抛出的错误(如果它抛出错误)并只给我该属性的空值/默认值?
最佳答案
创建将返回正确对象的类扩展
public static class CatExtensions
{
public static object GetObject(this Cat value)
{
return new
{
Hunger = value.Hunger,
Sleepiness = value.Sleepiness
}
}
}
关于c# - 序列化并忽略抛出异常的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32948998/