9

I have an [DataContract] object that has some properties and is serialized to JSON using DataContractJsonSerializer.

One of the properties is of type Dictionary<string, string> and when the serialization happens it produces the following JSON schema.

"extra_data": [
  {
    "Key": "aKey",
    "Value": "aValue"
  }
]

Now I need the JSON schema to be like this

"extra_data": { 
        "aKey": "aValue"
}

You can never of course know before what the values are, it is a Dictionary that the user will set keys and values.

I'm thinking if this can happen using anonymous types, or is there a configuration I can take to accomplish my goal?

Thank you.

1

1 Answer 1

3

Ok, let say you have:

[DataContract]
public class MyObject
{
    [DataMember(Name = "extra_data")]
    public Dictionary<string, string> MyDictionary { get; set; } 

}

Then you can use DataContractJsonSerializerSettings with UseSimpleDictionaryFormat set to true, something like this:

    var myObject = new MyObject { MyDictionary = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } } };

    DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true };

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyObject), settings);

    var result = string.Empty;

    using (MemoryStream ms = new MemoryStream())
    {
        serializer.WriteObject(ms, myObject);

        result = Encoding.Default.GetString(ms.ToArray());
    }
Sign up to request clarification or add additional context in comments.

5 Comments

Worked perfect and simple. Thank you.
For Windows Phone 8 I used the Newtonsoft JSON serializer Nuget package. james.newtonking.com/json
I dont have DataContractJsonSerializerSettings at all (running .NET 4.5), it just doest exist.
Hi, where can I replace the "normal" serializer with this serializier when I am create the service host in code?
DataContractJsonSerializerSettings is not available in .NET 4.0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.