【问题标题】:WCF DataContract: mapping JSON object to C# DictionaryWCF DataContract:将 JSON 对象映射到 C# 字典
【发布时间】:2017-07-17 08:55:51
【问题描述】:

我想将我通过 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,序列化器可以使用它来将 JSON 对象转换为Dictionary,而无需重写序列化器?

【问题讨论】:

    标签: c# python json wcf dictionary


    【解决方案1】:

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

    【讨论】:

    • 不幸的是,使用 List 不是我想要做的。字典将使我的界面更易于用户使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2019-08-03
    • 2012-02-15
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多