使用Microsoft命名空间System.Web.Helpers
和System.Web.Script.Serialization
时,我预计Microsoft序列化程序可以很好地与Microsofts动态JSON对象配合使用。事实证明,这是一个天真的假设。 JavaScriptSerializer将对象序列化为“{}”。这个看似微不足道的任务的推荐方法是什么?
dynamic obj = new DynamicJsonObject(new Dictionary<string,object>());
obj.FirstName = "Henry";
obj.LastName = "Ford";
JavaScriptSerializer jsc = new JavaScriptSerializer();
string str = jsc.Serialize( obj );
Assert.AreNotEqual(str, "{}"); // Does not fail
答案 0 :(得分:2)
尝试Json.Net
dynamic obj = new DynamicJsonObject(new Dictionary<string,object>());
obj.FirstName = "Henry";
obj.LastName = "Ford";
string str = JsonConvert.SerializeObject(obj);
它会成功完成。您可以将它与匿名类一起使用
string s = JsonConvert.SerializeObject(new {FirstName="Henry",LastName="Ford"});
和ExpandoObject
也是
dynamic obj = new ExpandoObject();
obj.FirstName = "Henry";
obj.LastName = "Ford";
string s = JsonConvert.SerializeObject(obj);
也可以对动态对象进行反序列化
dynamic obj2 = JsonConvert.DeserializeObject(@"{""FirstName"":""Henry"",""LastName"":""Ford""}");
Console.WriteLine(obj2.FirstName + " " + obj2.LastName);