2013-08-22 19 views
2

我試圖使用JavaScriptSerializer從JSON字符串反序列化下面的類的一個實例:JavaScriptSerializer:無法反序列化含HashSet的場地對象

public class Filter 
{ 
    public HashSet<int> DataSources { get; set; } 
} 

這裏是我嘗試的代碼:

 Filter f = new Filter(); 

     f.DataSources = new HashSet<int>(){1,2}; 

     string json = (new JavaScriptSerializer()).Serialize(f);   

     var g= (new JavaScriptSerializer()).Deserialize<Filter>(json); 

它的錯誤不與以下消息:

類型的對象「System.Collections.Generic.List 1[System.Int32]' cannot be converted to type 'System.Collections.Generic.HashSet 1 [System.Int32]'。

顯然,序列化程序無法區分列表和從JSON表示中設置。這有什麼解決辦法?

注意:由於工作上的限制,我寧願避免使用外部庫。

回答

4

這是什麼解決方案?

使用Json.Net。此代碼的工作...

Filter f = new Filter(); 

f.DataSources = new HashSet<int>() { 1, 2 }; 

string json = JsonConvert.SerializeObject(f); 

var g = JsonConvert.DeserializeObject<Filter>(json); 

編輯

DataContractJsonSerializer似乎太工作...

DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(Filter)); 
var g2 = dcjs.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json))) as Filter; 
+2

謝謝!但是我的工作需要我避免使用外部庫。任何使用.net的內置庫的解決方案都會很有幫助 – Aadith

+0

@ I4V'DataContractJsonSerializer'非常棒。謝謝! –

相關問題