I have a class with some data that I am serializing:
[Serializable]
public class SomeData {
public int NumericField;
public string StringField;
}
I have a convenient convenient extension method:
public static string ToJson<T> (this T value) {
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 would prefer to implement the class SomeData SomeData, but when I add it, I was told that 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 that I want her to do exactly what she is doing now, but also limit the classes ToJson<T>to ISerializable, so no one can ever accidentally pass something to her, an avoidable exception. Like this:
public static string ToJson<T> (this T value) where T : ISerializable
GetObjectData - , , , ISerializable? -, , , - ( ), , , [Serializable]. - . , .NET Framework 3.5.
UPDATE:
[DataContract] [Serializable], , ISerializable, , [DataContract] , ISerializable? ( qn, DataContract, Serializable)