序列化Dictionary时的JsonConvert意外行为

时间:2013-09-27 19:50:58

标签: c# json c#-4.0

全都好!我有一个Dictionary<string,Dictionary<CustomClass,string>>我想序列化。 我期望的结果是:

{
  "key1":{
          {
            "CustomClassProperty1":"val1",
            "CustomClassProperty2":"val2",
            "CustomClassProperty3":"val3"
          }:"Final STR",
          {
            "CustomClassProperty1":"val10",
            "CustomClassProperty2":"val2",
            "CustomClassProperty3":"val35"
          }:"Final STR4",
          {
            "CustomClassProperty1":"val100",
            "CustomClassProperty2":"val25",
            "CustomClassProperty3":"val300"
          }:"Final STR8"
         },
  "key2":{
          {
            "CustomClassProperty1":"val4",
            "CustomClassProperty2":"val5",
            "CustomClassProperty3":"val6"
          }:"Final STR 2"
         },
  "key3":{
          {
            "CustomClassProperty1":"val1",
            "CustomClassProperty2":"val7",
            "CustomClassProperty3":"val5"
          }:"Final STR 3",
          {
            "CustomClassProperty1":"val10",
            "CustomClassProperty2":"val2",
            "CustomClassProperty3":"val35"
          }:"Final STR0",
          {
            "CustomClassProperty1":"val100",
            "CustomClassProperty2":"val25",
            "CustomClassProperty3":"val300"
          }:"Final STR10"
         }
}

但相反,我正在

{
  "key1":{
          "MyProjectNamespace.CustomClass":"Final STR",
          "MyProjectNamespace.CustomClass":"Final STR4"
         },
  "key2":{
          "MyProjectNamespace.CustomClass":"Final STR 2"
         },
  "key3":{
          "MyProjectNamespace.CustomClass":"Final STR 3"
         }
}

谁能告诉我如何做对吗?我不想要“namespace.classname”但属性......我正在使用Newtonsoft.Json btw ...非常多!

1 个答案:

答案 0 :(得分:1)

您想要的输出不在JSON format:的左侧是对象属性的名称,必须是字符串。要获得您列出的格式,您需要使用另一个支持非JSON格式的序列化程序。