I have an object tree that I\'m serializing to JSON with DataContractJsonSerializer
. Dictionary
gets serialized but I don\'t li
Seems, there is no way to customize DataContractJsonSerializer.
If you still want to achieve what you want, consider using Json.Net. It's faster and more flexible than DataContractJsonSerializer. Look at JsonConverter conception of Json.Net. It gives you the possibility to customize serialization/deserialization process.
Moreover default implementation of dictionary serialization is exact as you want http://james.newtonking.com/projects/json/help/SerializingCollections.html.
One option is using a surrogate property and have the dictionary be inside the custom ISerializable type, that way you don't need to worry about inheritance:
public Dictionary<string, string> NodeData { get; set; }
[DataMember(Name="NodeData")]
private CustomDictionarySerializer NodeDataSurrogate
{
get
{
return new CustomDictionarySerializer(NodeData);
}
set
{
NodeData = value._data;
}
}
[Serializable]
private class CustomDictionarySerializer : ISerializable
{
public Dictionary<string, string> _data;
public CustomDictionarySerializer(Dictionary<string, string> dict)
{
_data = dict;
}
public CustomDictionarySerializer(SerializationInfo info, StreamingContext context)
{
_data = new Dictionary<string, string>();
var valueEnum = info.GetEnumerator();
while(valueEnum.MoveNext())
{
_data[valueEnum.Current.Name] = valueEnum.Current.Value.ToString();
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (var pair in _data)
{
info.AddValue(pair.Key, pair.Value);
}
}
}
As @Pashec mentioned, if you use Json.NET, you can try the following:
public Message <methodname> {
...
string jsonMessage = JsonConvert.SerializeObject(myObjectTree);
return WebOperationContext.Current.CreateTextResponse(jsonMessage, "application/javascript; charset=utf-8", Encoding.UTF8);
}