2

我有以下课程:

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 字符串反序列化为包含字典的强类型对象。

4

1 回答 1

0

To deserialize that into a Dictionary, the JSON would have to look a little different. It would have to define the Test class (loosely):

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

See, the dict definition exists in the JSON. However, what you have there could be deserialized directly into the Dictionary like this:

tt.dict = (Dictionary<string, string>)serializer.Deserialize(s,
    typeof(Dictionary<string, string>));
于 2013-10-22T00:55:01.807 回答