Sonar Qube Error Update this implementation of 'ISerializable' to conform to the recommended serialization pattern

1.7k views Asked by At

I'm currently working on a .net 4.6.2 application.

I need to serialize an OData Api call and it works perfectly fine.

Unfortunately I'm getting a Sonar Qube Error:

Update this implementation of 'ISerializable' to conform to the recommended serialization pattern.

enter image description here

To get my OData into C#, I use the following class structure:

[Serializable]
public class Record : Dictionary<string, dynamic> { }

[DataContract]
public class Records
{
    [DataMember(Name = "@odata.context")]
    public string Context { get; set; }

    [DataMember(Name = "@odata.count")]
    public int Count { get; set; }

    [DataMember(Name = "value")]
    public IEnumerable<Record> Value { get; set; }
}

The serialization works fine, but I don't know how to solve this Sonar Qube error.

How to properly use ISerializable together with DataContract, is it actually possible?

Do you know how to solve this issue?

3

There are 3 answers

2
Vivek Nuna On

As suggested by @Maritn Costello

you could suppress this warning like this.

#pragma warning disable S3925 // "ISerializable" should be implemented correctly
    public class Record : Dictionary<string, string> { }
#pragma warning restore S3925 // "ISerializable" should be implemented correctly

Dictionary class implement ISerializable

 public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, ISerializable, IDeserializationCallback
    {
0
Bender. On

In my case I chose to use the native type instead of a custom class. It works fine.

[DataMember(Name = "value")]
public List<Dictionary<string, dynamic>> Value { get; set; }
1
marie On

You need to add a protected constructor with arguments as follows:

SerializationInfo info, StreamingContext context

So the valid code is:

[Serializable]
public class Record : Dictionary<string, dynamic>
{
    protected Record(SerializationInfo info, StreamingContext context) : base(info, context)
    {

    }
}

[DataContract]
public class Records
{
    [DataMember(Name = "@odata.context")]
    public string Context { get; set; }

    [DataMember(Name = "@odata.count")]
    public int Count { get; set; }

    [DataMember(Name = "value")]
    public IEnumerable<Record> Value { get; set; }
}