[英]Unable to deserialize JSON to a Dictionary<string, List<string>> using JavaScriptSerializer
我在使用JavaScriptSerializer库在c#代码中反序列化JSON时遇到问题。
这是我的示例JSON:
{“ A”:[“ a”,“ b”,“ c”,“ d”],“ B”:[“ a”],“ C”:[]}
我正在使用字典来保存JSON,如下所示:
Dictionary<string, List<string>> myObject;
这就是我解析JSON并将其强制转换为对象的方式:
myObject= (Dictionary<string, List<string>>)jsc.DeserializeObject(json);
但是,在运行时,上一行将引发Casting异常,如下所示
无法转换类型为System.Collections.Generic.Dictionary2 [System.String,System.Object]的对象以类型为System.Collections.Generic.Dictionary2 [System.String,System.Collections.Generic.List1 [System.String]]
由于某种原因, JavaScriptSerializer
无法将具有字符串的JSON数组识别为List<string>
UPDATE
我用一些硬编码的字符串填充了我的Dictionary
数据结构,以查看序列化的版本。 原来正是我输入的JSON字符串是什么。
代替使用DeserializeObject
方法,而使用通用的Deserialize<T>
方法,并指定Dictionary<string, List<string>>
作为类型参数。 然后它将正常工作:
string json = @"{""A"":[""a"",""b"",""c"",""d""],""B"":[""a""],""C"":[]}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<string, List<string>> myObject =
serializer.Deserialize<Dictionary<string, List<string>>>(json);
foreach (KeyValuePair<string, List<string>> kvp in myObject)
{
Console.WriteLine(kvp.Key + ": " + string.Join(",", kvp.Value));
}
输出:
A: a,b,c,d
B: a
C:
问题是强制转换为List<string>
如果可以强制转换为对象,则可以这样做:
string json = "{\"A\":[\"a\",\"b\",\"c\",\"d\"],\"B\":[\"a\"],\"C\":[]}";
var serializer = new JavaScriptSerializer();
var deserializedValues = (Dictionary<string, object>)serializer.Deserialize(json, typeof(object));
我还建议研究Json.NET ,它在序列化/反序列化方面做得更好
根据JSON结构创建一个Type,然后像这样在序列化或反序列化中使用Type。
我使用Web Essentials Visual Studio扩展中的功能从JSON创建RootObject。
public class JSONSerializer
{
public void RunIt()
{
string json = "{\"A\":[\"a\",\"b\",\"c\",\"d\"],\"B\":[\"a\"],\"C\":[]}";
JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Rootobject jsonObject = serializer.Deserialize<Rootobject>(json);
Console.Write(serializer.Serialize(jsonObject));
}
}
public class Rootobject
{
public string[] A { get; set; }
public string[] B { get; set; }
public object[] C { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.