Problems with Json Serialize Dictionary

后端 未结 5 2488
自闭症患者
自闭症患者 2021-02-19 16:55

whenever i try to serialize the dictionary i get the exception:

System.ArgumentException: Type 
\'System.Collections.Generic.Dictionary`2[[Foo.DictionarySerializ         


        
相关标签:
5条回答
  • 2021-02-19 17:23

    I think that you are having trouble because TestEnum is declared as a private enum. Try marking it as a public enum. The serializer needs to be able to find your enum via reflection in order to serialize it.

    Also according to the Docs, the enums must have integer values. So you might want to write:

    public enum TestEnum { A = 1, B = 2, C =3 }
    

    Also, the docs say that this enum will just get mapped to its corresponding integer value during the serialization. So depending on what you are doing on the other end, Strings might be more expressive and easier to work with.

    0 讨论(0)
  • 2021-02-19 17:24

    Use Newtonsoft (Newtonsoft.Json.dll) to serialize the Dictionary object and you'd be fine. It's a popular third party library you would have to download and include in your project as a reference.

    See example below:

    var _validationInfos = new Dictionary<ImportField, ValidationInfo>();
    var serializedData = JsonConvert.SerializeObject(_validationInfos);
    
    0 讨论(0)
  • 2021-02-19 17:30

    Exception says "keys must be strings or object" so try

    data.Add(Enum.ToObject(typeof(TestEnum), TestEnum.A));
    data.Add(Enum.ToObject(typeof(TestEnum), TestEnum.B));
    data.Add(Enum.ToObject(typeof(TestEnum), TestEnum.C));
    

    I did not test it though, just a guess.

    0 讨论(0)
  • 2021-02-19 17:35

    I’ve created JavaScriptSerializer extension DeserializeDictionary- see http://geekswithblogs.net/mnf/archive/2011/06/03/javascriptserializer-extension-deserializedictionarytkey-tvalue.aspx

    public static Dictionary<TKey, TValue>  DeserializeDictionary<TKey, TValue>(this JavaScriptSerializer jss, string jsonText)
    {
        var dictWithStringKey = jss.Deserialize<Dictionary<string,TValue>>(jsonText);
        var dict=dictWithStringKey.ToDictionary(de => jss.ConvertToType<TKey>(de.Key),de => de.Value);
            return dict;
    }
    
    0 讨论(0)
  • 2021-02-19 17:46

    I know it's late, but maybe someone else can make use of it in the future. You can achieve what you need using LINQ:

    Dictionary<TestEnum, Int32> data = new Dictionary<TestEnum, Int32>();
    
    data.Add(TestEnum.A, 1);
    data.Add(TestEnum.B, 2);
    data.Add(TestEnum.C, 3);
    
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Dictionary<string, Int32> dataToSerialize = data.Keys.ToDictionary(p => p.ToString(), p => data[p]);
    string dataSerialized = serializer.Serialize(dataToSerialize);
    
    0 讨论(0)
提交回复
热议问题