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;
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 .
source share