Friday, March 13, 2015

Json.NET Error: Could not create an instance of type IAmAnInterface

While using NewtonSoft's excellent Json.NET library, I was trying to deserialize a dictionary containing interface objects and got this error message:

"Could not create an instance of type IAmAnInterface. Type is an interface or abstract class and cannot be instantiated. "

Fortunately Json.NET has a very easy way around this by telling it to save the type metadata in the output.  To serialize the dictionary:



        static readonly Object Locker = new object();
        public void Save()
        {
            lock (Locker)
            {
                File.WriteAllText(reportFilePath,
                    JsonConvert.SerializeObject(_dictionary, Formatting.Indented, new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.Objects,
                        TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
                    }));
            }
        }


To bring the objects back:

         public void Load()
        {
            _dictionary = JsonConvert.DeserializeObject>(File.ReadAllText(reportFilePath),
                new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects
                });
        }



This does make the json file larger, but for us, it's well worth the price.






No comments: