序列化抛出NotImplementedException的属性

Jes*_*alm 4 c# serialization json.net

有没有办法序列化以下类的对象,并以某种方式忽略抛出的异常?

public class HardToSerialize
{
  public string IAmNotTheProblem { get; set; }
  public string ButIAm { get { throw new NotImplementedException(); } }
}
Run Code Online (Sandbox Code Playgroud)

并不奇怪的是,当Newtonsoft尝试序列化该ButIAm属性的值时会抛出错误.

我无法访问该类,因此我无法使用任何属性来装饰它.

澄清:我希望这适用于任何具有抛出NotImplementedException属性的对象.这个HardToSerialize课只是一个例子.

Jes*_*alm 6

我找到了一个适合我的解决方案.这样做有什么重大问题吗?

var settings = new JsonSerializerSettings();
settings.Error += (o, args) => {
    if(args.ErrorContext.Error.InnerException is NotImplementedException)
        args.ErrorContext.Handled = true;
};

var s = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented, settings);
Run Code Online (Sandbox Code Playgroud)