2014-02-28 36 views
1

以下是我想要使用本地JavaScript支持反序列化爲Dictionary的JSON。 。將JSON數據反序列化爲字典時出錯<string,string>

string data = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}"; 

但是,當我嘗試使用以下代碼

字典的值進行反序列化=新System.Web.Script.Serialization.JavaScriptSerializer()反序列>(數據);

它給了我一個錯誤,說明 "Type 'System.String' is not supported for deserialization of an array"

我使用.NET Framework 3.5。請幫我完成這件事。

回答

0

我想你不能直接將其轉換成一個字典...我認爲deserializer需要一個相應的類型,與類型可理解的屬性名稱,

我想你可以轉換爲type,然後生成您的dictionary ,是這樣的:

public class MyClass 
    { 
     public List<bool> Symptom { get; set; } 
     public List<bool> Action { get; set; } 
     public bool AllArea { get; set; } 

     public Dictionary<string, List<bool>> getDic() 
     { 
      // this is for example, and many many different may be implement 
      // maybe some `reflection` for add property dynamically or ... 

      var oDic = new Dictionary<string, List<bool>>(); 
      oDic.Add("Symptom", this.Symptom); 
      oDic.Add("Action", this.Action); 
      oDic.Add("AllArea", new List<bool>() { AllArea }); 
      return oDic; 
     } 
    } 

則:

string data = "{\"Symptom\":[true,true,true],\"Action\":[true,true],\"AllArea\":true}"; 
System.Web.Script.Serialization.JavaScriptSerializer aa = new System.Web.Script.Serialization.JavaScriptSerializer(); 
var o = aa.Deserialize<MyClass>(data); 
var dic = o.getDic(); 

無論如何,這是一個很好闕stion

相關問題