繁体   English   中英

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

[英]deserialize json to strongly typed object containing a 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字符串反序列化为包含字典的强类型对象。

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

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

请参阅, dict定义存在于JSON中。 但是,您可以将其中的内容直接反序列化为以下Dictionary

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM