0

我在下面foreach的代码段语句中遇到了以下异常:

异常:System.InvalidCastException:无法从源类型转换为目标类型。

我仔细看了看LitJson.JsonData。它确实有internal class OrderedDictionaryEnumerator : IDictionaryEnumerator实现。我不确定缺少什么。有任何想法吗?

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

1 回答 1

1

该类LitJson.JsonData声明为:

public class JsonData : IJsonWrapper, IEquatable<JsonData>

反过来IJsonWrapper又从这两个接口派生:System.Collections.IListSystem.Collections.Specialized.IOrderedDictionary.

请注意,这两个都是非通用集合版本。枚举时,您不会得到 aKeyValuePair<>结果。相反,它将是一个System.Collections.DictionaryEntry实例。

因此,您必须将您的更改foreach为:

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;
}
于 2015-05-19T00:47:57.710 回答