Serialize Dictionary to JSON with DataContractJsonSerializer

后端 未结 3 953
余生分开走
余生分开走 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: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 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 _data;
    
        public CustomDictionarySerializer(Dictionary dict)
        {
            _data = dict;
        }
    
        public CustomDictionarySerializer(SerializationInfo info, StreamingContext context)
        {
            _data = new Dictionary();
            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);
            }
        }
    }
    

提交回复
热议问题