[英]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.