将json反序列化为包含字典的强类型对象

时间:2013-10-22 00:30:46

标签: c# .net json serialization dictionary

我有以下课程:

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
   }

所以问题是如何将像“{hello”:“divya”,“bye”:“divya”}这样的json字符串反序列化为包含字典的强类型对象。

1 个答案:

答案 0 :(得分:0)

要将其反序列化为Dictionary,JSON必须看起来有点不同。它必须定义Test类(松散地):

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

请参阅JSON中存在dict定义。但是,您可以将直接直接反序列化到Dictionary中,如下所示:

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