I have a class with some data I'm serializing:
[Serializable]
public class SomeData {
public int NumericField;
public string StringField;
}
I have a nice convenient extension method:
public static string ToJson<T> (this T value) {
// yay no compile-time checks for [Serializable]?
if (!typeof(T).IsSerializable)
throw new SerializationException("Object lacks [Serializable] attribute");
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream()) {
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8)) {
serializer.WriteObject(writer, value);
}
return Encoding.UTF8.GetString(stream.ToArray());
}
}
I'd really rather my class SomeData
implemented ISerializable
, but when I add it, I'm told I need to add a method:
error CS0535: 'SomeData' does not implement interface member
System.Runtime.Serialization.ISerializable.GetObjectData(
System.Runtime.Serialization.SerializationInfo,
System.Runtime.Serialization.StreamingContext)'
The problem is just that I want it to do exactly what it currently does, but also restrict ToJson<T>
to ISerializable
classes so no one will ever accidentally pass it something that would throw an avoidable exception. Like this:
public static string ToJson<T> (this T value) where T : ISerializable
Is there a concise implementation of GetObjectData
or some other trick that will just replicate the exact behavior I would get if I don't add the ISerializable
interface? I want something I can just include in a class I inherit, or something concise (and always exactly the same) I can just paste into all the classes where I just want exactly what [Serializable]
does to happen. Something generic. Performance is not a huge concern, but I can only use .Net Framework 3.5.
UPDATE:
I'm perfectly willing to use [DataContract]
in the place of [Serializable]
, but if I did that, is there a generic way I could implement ISerializable
so it just does exactly what [DataContract]
would do if I hadn't implemented ISerializable
? (same qn as above with DataContract
everywhere you see Serializable
)