WCF DataContract:将JSON对象映射到C#Dictionary

时间:2017-07-17 08:55:52

标签: c# python json wcf dictionary

我想将通过HTTP从python应用程序收到的JSON字典反序列化为C#中的Dictionary

JSON对象如下所示:

{
    "native_dict": {
        "foo": 0,
        "bar": 1
    },
    "obj_dict": [
        {"Key": "foo", "Value": 0},
        {"Key": "bar", "Value": 1},
    ]
}

它包含两次传递字典的尝试。第一种是原生JSON格式,第二种似乎是C#需要的格式。

两者都将转换为这种XML格式:

<root type="object">
  <value type="object">

    <native_dict type="object">
      <bar type="number">1</bar>
      <foo type="number">0</foo>
    </native_dict>

    <obj_dict type="array">
      <item type="object">
        <Value type="number">0</Value>
        <Key type="string">foo</Key>
      </item>
      <item type="object">
        <Value type="number">1</Value>
        <Key type="string">bar</Key>
      </item>
    </obj_dict>

  </value>
</root>

在我的应用程序中,我尝试了这些DataContracts:

[DataContract]
public class MyDto
{
    [DataMember(Name = "native_dict")]
    private Dictionary<string, int> MyDict1 { get; set; }

    [DataMember(Name = "obj_dict")]
    private MyDictionary<string, int> MyDict1 { get; set; }
}

[CollectionDataContract
    (Name = "obj_dict",
    ItemName = "item"
    KeyName = "Key", 
    ValueName = "Value")]
public class MyDictionary: Dictionary<string, int> { }

没有一个可以解决。

有没有办法定义一个DataContract,Serializer可以用来将JSON对象转换为Dictionary,而无需重写Serializer?

1 个答案:

答案 0 :(得分:0)

我通常会根据您的情况使用List而不是Dictionary。您创建一个类型为List的属性,其中objectItem是一个具有键和值作为自己的属性的类。 WCF datacontract会将传入的json字符串反序列化为c#list object。