JavaScriptSerializer:对象引用没有设置为对象的实例
本文关键字:对象 实例 设置 对象引用 JavaScriptSerializer | 更新日期: 2023-09-27 18:12:37
我哪里做错了?
using System.Web.Script.Serialization;
string json = "{'"numbers'":[{'"one'":'"1'"},{'"two'":'"2'"},{'"three'":'"3'"}]}";
dynamic dictionary = new JavaScriptSerializer().Deserialize<dynamic>(json);
Assert.AreEqual(3, dictionary["numbers"].Count);
System.NullReferenceException : Object reference not set to an instance of an object
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToObject (IDictionary`2 dict, System.Type type) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToList (System.Collections.ArrayList col, System.Type type) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToObject (IDictionary`2 dict, System.Type type) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType (System.Type type, System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.ConvertToType[Object] (System.Object obj) [0x00000] in <filename unknown>:0
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[Object] (System.String input) [0x00000] in <filename unknown>:0
我看你的代码没有问题,除了使用count属性,而且由于json被反序列化时代码会中断,我建议你使用静态类型定义代替,只是为了缩小问题的变化与你的代码:
string json = "{'"numbers'":[{'"one'":'"1'"},{'"two'":'"2'"},{'"three'":'"3'"}]}";
var dictionary = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
也许只是也许在JavaScriptSerializer中使用动态类型存在问题,如果JavaScriptSerializer确实存在问题,您可以随时向MSFT报告。
由于我不能使Dictionary<string, object>
工作,我决定放弃它并使用静态类型代替。顺便说一句,这个在线工具非常方便,可以从JSON生成c#类。