简体   繁体   中英

newtonsoft json deserialize dictionary

I have the following class

 [DataContract(IsReference = true)] 
 public abstract class Entity
 {
     [DataMember]
     protected Dictionary<MyStruct, MyObject> MyDict;

     ... 
 }

I try to serialize and Deserialize using newtonsoft Json, Serialization works . But on deserializn I get the following error : "Create a TypeConverter to convert from the string to the key type" , and when I create a type convertor it is not called by the deseializer.

This is how I use the JSON serializer

StringBuilder sb = new StringBuilder();
TextWriter text = new StringWriter(sb);

var serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.Auto;

var inst = new Instance();
serializer.Serialize(text, inst );

TextReader textReader = new StringReader(sb.ToString());
JsonReader reader = new JsonTextReader(textReader);
var res = serializer.Deserialize(reader, typeof(Instance));

The Json serializer treats the keys as strings, not as objects . the serializer has some attributes you can use you can do the following :

 [JsonObject()]
 public class MyDictionaryType : Dictionary<MyStruct, MyObject>
 {
 }


 [DataContract(IsReference = true)] 
 public abstract class Entity 
 {
     [DataMember]
     protected MyDictionaryType  MyDict;

     ... 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM