2

I would like to deserialize a JSON dictionary I receive from a python application via HTTP into a Dictionary in C#.

The JSON object looks like this:

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

It contains two attempts of passing the dictionary. The first would be the native JSON format and the second seemed to be the format C# needs.

Both will be converted to this XML format:

<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>

In my application I tried these 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> { }

None of them can be resolved.

Is there a way to define a DataContract that the Serializer can use to convert the JSON object to a Dictionary, without rewriting the Serializer?

1 Answer 1

1

I usually use List instead of Dictionary for your case. You create a property with type List where objectItem is a class having key and value as own properties. WCF datacontract will deserialize the incoming json string into c# list object.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately using a List is not what I want to do. The Dictionary would make my Interface a lot easier to use for the users.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.