Deserializing a List of Objects that contain a Dictionary

后端 未结 3 506
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 09:06

I\'ve seen a lot of examples that seem to indicate that what I\'m doing should work, but for whatever reason, it doesn\'t. I\'m trying to deserialize a collection of objects

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 09:51

    Looks like Dictionary is not serializable the way you'd expect. I tried List> instead, and that doesn't seem to work either.

    Only thing I can think of is some ugly stuff that will convert your JSON into a custom type, and then convert it into a dictionary. So using your 2nd JSON example exactly as-is, you can do something like:

    // Inside of MyObject class
    [DataMember]
    public Kvp[] Dictionary { get; set; }
    
    public Dictionary GetDictionary()
    {
        return Dictionary.ToDictionary(x => x.Key, x => x.Value);
    }
    
    //////////////////
    
    public class Kvp
    {
        public T1 Key { get; set; }
        public T2 Value { get; set; }
    }
    
    Dictionary myDictionary = myObjects[0].GetDictionary();
    

    I'm sure there's a much better way, but this should at least work.

提交回复
热议问题