0

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 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.