【问题标题】:deserialize json to strongly typed object containing a dictionary将 json 反序列化为包含字典的强类型对象
【发布时间】:2013-10-30 16:28:41
【问题描述】:

我有以下课程:

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

【问题讨论】:

  • 您正在序列化字典并反序列化为您的 Test 类型。这不匹配。

标签: c# .net json serialization dictionary


【解决方案1】:

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

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

看,dict 定义存在于 JSON 中。但是,您所拥有的内容可以直接反序列化为Dictionary,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多