Serialize property that throws NotImplementedException

Is there any way to serialize objects of the next class and somehow ignore the generated exception?

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

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

I do not have access to the class, so I can not decorate it with any attributes.

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

+4
source share
3 answers

I found a solution that worked for me. Are there any serious issues with 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); 
+6
source

I would go for a surrogate class and custom JsonConverter :

 public class HardToSerializeSurrogate { public string IAmNotTheProblem { get; set; } public string ButIAm { get; set; } } public class HardToSerializeConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(HardToSerialize); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var item = (HardToSerialize)value; // fill the surrogate with the values of the original object var surrogate = new HardToSerializeSurrogate(); surrogate.IAmNotTheProblem = item.IAmNotTheProblem; serializer.Serialize(writer, surrogate); } } 

Using:

 static void Main(string[] args) { var hardToSerialize = new HardToSerialize() { IAmNotTheProblem = "Foo" }; var s = JsonConvert.SerializeObject(hardToSerialize, new HardToSerializeConverter()); } 

Of course, implementing a custom JsonConverter really worth it if you have to serialize a list of HardToSerialize objects or an object that contains this type.
On the other hand, if you just want to serialize one HardToSerialize object each time, just create a surrogate copy of the object and serialize it without implementing a custom JsonConverter .

+2
source

A possible workaround would be to create another object from EasyToSerialize and then serialize it.

 [Serializable] public class EasyToSerialize { public string IAmNotTheProblem { get; set; } // other serializable properties } HardToSerialize x = ...; var foo2 = new EasyToSerialize { IAmNotTheProblem = x.IAmNotTheProblem // other properties here }; 
+1
source

All Articles