Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize property that throws NotImplementedException

Is there any way to serialize objects of the following class and somehow ignore the exception being thrown?

public class HardToSerialize
{
  public string IAmNotTheProblem { get; set; }
  public string ButIAm { get { throw new NotImplementedException(); } }
}

Not suprisingly Newtonsoft throws an error when it tries to serialize the value of the ButIAm property.

I don't have access to the class so I can't decorate it with any attributes.

Clarification: I want this to work for any object that has properties that throws a NotImplementedException. The HardToSerialize class is just one example.

like image 885
Jesper Palm Avatar asked Dec 10 '12 21:12

Jesper Palm


1 Answers

I found a solution that worked for me. Is there any major problems doing it like this?

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);
like image 53
Jesper Palm Avatar answered Nov 14 '22 22:11

Jesper Palm