Deserialize json array to IEnumerable

Mar 1, 2009 at 4:14 PM
I am trying to deserialize a json array to an IEnumerable but get an error stating that it does not know hot to deserialize to an IEnumerable which makes sense as it does not know which concrete implementation to use.
Is there any way I can let the serializer know that I want it to use a list when it see an IEnumerable through an attribute or a property?

Thanks
Coordinator
Mar 2, 2009 at 7:57 AM
Seems like a reasonable thing to do.

I will update JsonSerializer so it knows to create a List<T> for IEnumerable<T>, ICollection<T>, etc when deserializing. I'm making fairly large changes at the moment and I don't know when it will get checked into CodePlex for you to get. I'll post here when it is.
Mar 2, 2009 at 9:23 AM
Fantastic!! Thanks a lot. No rush. I've got a workaround at the moment.
Coordinator
Mar 14, 2009 at 12:43 AM
Source code is in CodePlex if you want to grab it and build a copy.

http://json.codeplex.com/SourceControl/ListDownloadableCommits.aspx
Mar 16, 2009 at 1:32 PM
Much appreciated. So far everything seems fine.
Mar 23, 2009 at 4:25 PM
This is working however there are a few caveats:

1.  A conversion from string to Enum does not work, however, if you have a custom type that is an Enum the conversion works.

** This signature causes an exception to be thrown while deserializing **
public class MyDictionary : Dictionary<Enum, string>

** This signature works correctly while deserializing **
public class MyDictionary : Dictionary<ConfigKey, string>, where "public enum ConfigKey { ... };"

2.  When adding a key, value pair to the DictionaryWrapper class there is an assumption that the internal type does not have any existing pairs.
     However, in my case, my dictionary tries to auto load configuration during initialization, if it finds anything it loads itself.  This causes
     the wrapper to throw an exception due to duplicate keys trying to be added.  To get around this a code change can be made to
     check for duplicate keys.  This is how I modified the wrapper to eliminate this exeception. 

    if( this._genericDictionary != null && !this._genericDictionary.ContainsKey((TKey)key) )
        this._genericDictionary.Add((TKey)key, (TValue)value);
    //This check is now necssary if the _genericDictionary already contains the key.
    else if( this._dictionary != null )
        this._dictionary.Add(key, value);

There are a few add methods so depending on how the dictionary gets deserialized you may need to change one or more of them.

Coordinator
Mar 23, 2009 at 9:48 PM
Edited Mar 23, 2009 at 10:02 PM
The first example will never work. Json.NET doesn't know what value type to create when it encounters an Enum.
Coordinator
Mar 24, 2009 at 8:16 AM
mkrain could post an example of the JSON that is causing your second issue? I want to investigate it deeper before modifying any code.