Why is the ISerializable interface not supported?

Aug 20, 2009 at 11:30 AM

I have a class that implements System.Runtime.Serialization.ISerializable but the GetObjectData method is not called during serialization, neither is a (non-public) ctor with the signature (SerializationInfo information, StreamingContext context). Can someone please explain if I can work around this problem by using a converter or something?

Thanks, J.

Coordinator
Aug 20, 2009 at 10:03 PM
Edited Aug 21, 2009 at 2:40 AM

It isn't supported at the moment. I'll investigate adding it in the future but it won't be happening soon.

Aug 21, 2009 at 10:21 AM

What a shame because this would bring some .NET serialization standardization into JSON.NET. In fact, you should also implement System.Runtime.Serialization.Formatter on JsonSerializer. Anyways, I have a working (very rough) SerializationConverter (see code below) in case you're interested ;-) Let me know if you see any problems with it.

Cheers, J.

        public class SerializableConverter : JsonConverter
       
{
            private IFormatter formatter;

            internal SerializableConverter(IFormatter formatter)
            {
                this.formatter = formatter;
            }

            public override bool CanConvert(Type objectType)
            {
                return (typeof(ISerializable).IsAssignableFrom(objectType));
            }

            public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
            {
                SerializationInfo si = new SerializationInfo(objectType, new FormatterConverter());
                var obj = JObject.Load(reader);
                foreach (var p in obj.Properties())
                {
                    object value = ((JValue) obj[p.Name]).Value;
                    si.AddValue(p.Name, value);
                }
                return TypeUtils.CreateObject(objectType, si, formatter.Context);
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                SerializationInfo si = new SerializationInfo(value.GetType(), new FormatterConverter());
                ((ISerializable) value).GetObjectData(si, formatter.Context);
                JObject obj = new JObject();
                foreach (var e in si)
                {
                    obj[e.Name] = JToken.FromObject(e.Value);
                }
                serializer.Serialize(writer, obj);
            }

        }