0

Could please someone explain me why Deserialize method fails ?

        [Test]
        public void Serialize_Deserialize_ExpandObject()
        {
            dynamic obj = new ExpandoObject();
            obj.Name = "Claudio";
            obj.Age = 32;

            JavaScriptSerializer ser = new JavaScriptSerializer();
            string json = ser.Serialize(obj as IDictionary<string, object>);
            Console.WriteLine(json);

            IDictionary<string, object> deserialize = ser.Deserialize<IDictionary<string, object>>(json);
            Assert.IsTrue(deserialize.ContainsKey("Name"));
            Assert.IsTrue(deserialize.ContainsKey("Age"));
        }
jitidea
  • 294
  • 1
  • 13

1 Answers1

0

It seems as though ExpandoObject gets serialized as an array (of dictionaries) rather than a dictionary.

It gets serialized as [{"Key":"Name","Value":"Claudio"},{"Key":"Age","Value":32}] rather than {"Name":"Claudio","Age":32}

I guess there is some other interface that ExpandoObject implements like IEnumerable (as well as IDictionary<>) so the Serialize method treats it as an array. The cast (as IDictionary<string, object>) makes no difference because it doesn't actually alter what gets passed to the Serialize method. But this all seems to contradict the documentation http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx.

You can deserialize to List<IDictionary<string, object>> but I suppose thats not terribly useful.

Steve
  • 15,606
  • 3
  • 44
  • 39