Unity LitJson.JsonData exception on cast in foreach loop

1.7k Views Asked by At

I got the following exception in the foreach statement of my code snippet below:

exception:System.InvalidCastException: Cannot cast from source type to destination type.

I took a closer look at LitJson.JsonData. It does have the internal class OrderedDictionaryEnumerator : IDictionaryEnumerator implementation. I am not sure what is missing. Any ideas?

protected static IDictionary<string, object> JsonToDictionary(JsonData in_jsonObj)
{
    foreach (KeyValuePair<string, JsonData> child in in_jsonObj)
    {
        ...
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

The LitJson.JsonData class is declared as:

public class JsonData : IJsonWrapper, IEquatable<JsonData>

Where the IJsonWrapper in turn derives from these two interfaces: System.Collections.IList and System.Collections.Specialized.IOrderedDictionary.

Note that both of these are the non-generic collection versions. When enumerating you are not going to get a KeyValuePair<> as the result. Instead, it will be a System.Collections.DictionaryEntry instance.

So you will have to change your foreach to:

foreach (DictionaryEntry child in in_jsonObj)
{
    // access to key
    object key = child.Key;
    // access to value
    object value = child.Value;

    ...

    // or, if you know the types:
    var key = child.Key as string;
    var value = child.Values as JsonData;
}