Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a dictionary using DataContractJsonSerializer?

I have the following model:

[DataContract]
public class MessageHeader
{
    private Guid? messageId;

    public Guid MessageId
    {
        get
        {
            if (messageId == null)
                messageId = Guid.NewGuid();

            return messageId.Value;
        }
    }

    [DataMember]
    public string ObjectName { get; set; }

    [DataMember]
    public Dictionary<string, object> Parameters { get; set; } // Can't deserialize this

    [DataMember]
    public Action Action { get; set; }

    [DataMember]
    public User InitiatingUser { get; set; }
}

Now for some unknown reason, DataContractJsonSerializer can't deserialize JSON into a dictionary (See additional details section).
Unfortunately DataContractJsonSerializer is also sealed for reasons that are beyond me.
I need a way to get around it, does anyone got a clue?

like image 345
the_drow Avatar asked Nov 16 '10 21:11

the_drow


1 Answers

Since there isn't a dictionary type in javascript it's rather difficult to have JSON deparse into one. What you're going to have to do is write a converter yourself.

However, that's also true on most custom serialization objects, so hopefully that comes as no big surprise.

Now it should, however, read in as a KeyValuePair so you can try that, to see if it's at least deserializing for you. Rather, you would need a List<KeyValuePair<>>

What a Dictionary<string,string> translates into for JSON:

var dict = new Dictionary<string,string>; 
dict["Red"] = "Rosso"; 
dict["Blue"] = "Blu"; 
dict["Green"] = "Verde";

[{"Key":"Red","Value":"Rosso"},
 {"Key":"Blue","Value":"Blu"},
 {"Key":"Green","Value":"Verde"}]

The same associative from javascript into JSON:

var a = {}; 
a["Red"] = "Rosso"; 
a["Blue"] = "Blu"; 
a["Green"] = "Verde";

{"Red":"Rosso","Blue":"Blu","Green":"Verde"}

So there's the problem in a nutshell.


A few followup links for usefulness

http://my6solutions.com/post/2009/06/17/The-serialization-and-deserialization-of-the-generic-Dictionary-via-the-DataContractJsonSerializer.aspx

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.collectiondatacontractattribute.aspx

like image 79
jcolebrand Avatar answered Sep 28 '22 04:09

jcolebrand