0

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?

Bender.
  • 71
  • 6

3 Answers3

1

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
    {
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
1

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; }
}
marie
  • 180
  • 1
  • 8
  • and the key point is you need the attribute `Serializable` and the protected constructor – marie Apr 06 '23 at 03:12
0

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; }
Bender.
  • 71
  • 6