2013-10-22 132 views
2

我有下面的類:反序列化JSON來強類型的對象包含字典

public class Test 
{ 

    public Dictionary<string, string> dict = new Dictionary<string, string>(); 

    public static void main(String args[]){ 

     var serializer = new JavaScriptSerializer(); 
     Test tt = new Test(); 
     tt.dict.Add("hello","divya"); 
     tt.dict.Add("bye", "divya"); 
     String s = serializer.Serialize(tt.dict); // s is {"hello":"divya","bye":"divya"} 

     Test t = (Test)serializer.Deserialize(s,typeof(Test)); 
     Console.WriteLine(t.dict["hello"]); // gives error since dict is empty 
    } 

所以,問題是怎麼做的我反序列化JSON字符串像{「你好」:「迪夫亞」,「再見」: 「divya」}轉換爲包含字典的強類型對象。

+1

您序列化字典和反序列化到你的'Test'類型。那不匹配。 – Gigo

回答

0

要將其反序列化爲Dictionary,JSON必須看起來有點不同。它必須定義Test類(寬鬆):

{ 
    dict: { 
     "hello": "divya", 
     "bye": "divya" 
    } 
} 

看到,dict定義在JSON存在。但是,你有什麼有可能被直接反序列化Dictionary這樣的:

tt.dict = (Dictionary<string, string>)serializer.Deserialize(s, 
    typeof(Dictionary<string, string>)); 
相關問題