0

I'm building WCF REST service and I've noticed that when I pass JSON object with colons as key names and try to deserialize these pairs as a dictionary, then nothing happens. Deserialization in REST service executes without errors, but object fields which corresponding key names in JSON object containing colons just don't become deserialized.

I've found that the problem is with DataContractJsonSerializer and custom dictionary class. I've found serializable dictionary here Generic WCF JSON Deserialization), it just doesn't want to parse keys with colons.

Here's an example

void Main()
{
    var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(
        @"{ ""a:b:c"": ""adfsfsf"", ""res"": 123, ""dict"": { ""a:b"": ""va"", ""b"": ""vb"" } }"));
    var ser = new DataContractJsonSerializer(typeof(A));
    var a = (A)ser.ReadObject(stream);
    a.Dump();
}

[DataContract]
class A 
{
    [DataMember(Name = "a:b:c")]
    public string AF { get; set; }

    [DataMember(Name = "res")]
    public int Res { get; set; }

    [DataMember(Name = "dict")]
    public JsonDictionary Dict { get; set; } 
}

// NOTE: Code from https://stackoverflow.com/questions/2297903/generic-wcf-json-deserialization
[Serializable]
public class JsonDictionary : ISerializable
{
    private Dictionary<string, string> m_entries;

    public JsonDictionary()
    {
        m_entries = new Dictionary<string, string>();
    }

    public IEnumerable<KeyValuePair<string, string>> Entries
    {
        get { return m_entries; }
    }

    protected JsonDictionary(SerializationInfo info, StreamingContext context)
    {
        m_entries = new Dictionary<string, string>();
        foreach (var entry in info)
        {
            m_entries.Add(entry.Name, (string)entry.Value);
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        foreach (var entry in m_entries)
        {
            info.AddValue(entry.Key, entry.Value);
        }
    }
}    

As a result I get and instance of A with filled fields a:b:c and res. But in dictionary I get only 1 pair (it's b/vb). And the pair a:b/va just don't appear in result dictionary. And if I rename a:b to a. then a/va appears in dictionary.

What can be wrong?

Community
  • 1
  • 1
Dmitrii Lobanov
  • 4,897
  • 1
  • 33
  • 50
  • 1
    Have you tried JSON.NET ? I know it is a change of direction, but in a lot of cases it just *does a better job* – Marc Gravell Jul 21 '12 at 20:57
  • @MarcGravell: I've switched from passing data as class to raw representation (as Stream) and manual parsing using JSON.NET. It works. So now I don't deal with DataContractSerializer on arguments deserializing. But I still use it to return result, but there's no complex data in result :). Thanks! – Dmitrii Lobanov Jul 24 '12 at 12:10

0 Answers0