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

C# 将json反序列化为包含字典的强类型对象,c#,.net,json,serialization,dictionary,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();

我有以下课程:

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
   }
公共类测试
{
公共字典dict=新字典();
公共静态void main(字符串参数[]){
var serializer=新的JavaScriptSerializer();
测试tt=新测试();
tt.dict.Add(“你好”,“迪维亚”);
tt.dict.Add(“拜拜”、“迪维亚”);
字符串s=serializer.Serialize(tt.dict);//s是{“hello”:“divya”,“bye”:“divya”}
Test t=(Test)序列化程序。反序列化(s,typeof(Test));
Console.WriteLine(t.dict[“hello”]);//由于dict为空,因此给出错误
}

因此,问题是如何将类似{“hello”:“divya”,“bye”:“divya”}的json字符串反序列化到包含字典的强类型对象中。

要将其反序列化到
字典中,json必须看起来有点不同。它必须定义
测试
类(松散地):

请参阅,JSON中存在
dict
定义。但是,您所拥有的内容可以直接反序列化到
字典中,如下所示:

tt.dict = (Dictionary<string, string>)serializer.Deserialize(s,
    typeof(Dictionary<string, string>));
tt.dict=(字典)序列化程序。反序列化,
类型(字典);

您正在序列化字典并反序列化到您的
测试类型中。这不匹配。
tt.dict = (Dictionary<string, string>)serializer.Deserialize(s,
    typeof(Dictionary<string, string>));