How to implement ISerializable in a class using [Serializable] when I want to do what it would do if I hadn't added ISerializable?

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) {
    // 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 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)

+3
3

ISerializable, SerializationException . DataContractJsonSerializer , . :

  • Serializable
  • DataContract
  • ISerializable
  • Nothing ( )

.

:

( , # 5.0). Serializable ISerializable , .

+5
  • , . ISerializable #

  • - , ISerializable

0

To work around this behavior, implement the ISerializable.GetObjectData method in the converted Visual C # .NET class. To do this, add the following code to the converted Visual C # .NET class:

void System.Runtime.Serialization.ISerializable.GetObjectData(
    System.Runtime.Serialization.SerializationInfo info,
    System.Runtime.Serialization.StreamingContext context)
{
    // Code as required
}
0
source

All Articles