0

I'm creating a WCF service that will accept data that looks like this:

[DataContract]
public class Payload
{
    [DataMember]
    public string Prop1 { get; set; }
    [DataMember]
    public string Prop2 { get; set; }
    [DataMember]
    public List<Dictionary<string,string>> Prop3 { get; set; }
}

However, when I submit this data:

{"Prop1":"A","Prop2":"B","Prop3":[{"Prop4":"D","Prop5":"E"},{"Prop6":"F","Prop7":"G"}]}

The deserialized object has Prop1 and Prop2 filled out correctly, and Prop3 contains two Dictionary objects - but both Dictionaries are empty.

I also changed Prop3 to use an internal class:

public List<PayloadData> Prop3 { get; set; }

[DataContract]
public class PayloadData : ISerializable, IEnumerable<KeyValuePair<string,string>>
{
    private readonly Dictionary<string,string> _dict;

    public PayloadData()
    {
        _dict = new Dictionary<string,string>();
    }

    ...
}

This had the same result. I also tried making the PayloadData class implement both ICollection<KeyValuePair<string,string>> and IDictionary<string,string> with no luck.

Adam V
  • 6,256
  • 3
  • 40
  • 52
  • 1
    Related: http://stackoverflow.com/questions/1510185/how-to-serialize-dictionarystring-string-through-wcf – Yacoub Massad May 24 '16 at 21:37
  • The problem is that WCF uses `DataContractJsonSerializer`, and the latter serializes dictionaries as arrays, not objects. See [Any way to make DataContractJsonSerializer serialize Dictionaries properly?](http://stackoverflow.com/questions/4559991). While it is possible to override this behavior in WCF, it is quite difficult. See for instance [Using Custom WCF Body Deserialization without changing URI Template Deserialization](https://stackoverflow.com/questions/33554997). – dbc May 25 '16 at 00:15
  • To work around this incompatibility on the client side, you could use `DictionaryToArrayConverter` from [Usage-specific serialization for complex type in Dictionary with JSON.Net](https://stackoverflow.com/questions/27332723). And for deserialization on the Json.NET side, see [Newtonsoft Json Deserialize Dictionary as Key/Value list from DataContractJsonSerializer]((https://stackoverflow.com/questions/28451990). – dbc May 25 '16 at 00:18

0 Answers0