Serialize Dictionary to JSON with DataContractJsonSerializer

后端 未结 3 952
余生分开走
余生分开走 2021-01-04 03:18

I have an object tree that I\'m serializing to JSON with DataContractJsonSerializer. Dictionary gets serialized but I don\'t li

相关标签:
3条回答
  • 2021-01-04 03:34

    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.

    0 讨论(0)
  • 2021-01-04 03:50

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-04 03:59

    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);
    }
    
    0 讨论(0)
提交回复
热议问题