![](/img/trans.png)
[英]c# With Unity and LitJSON Getting an Invalid Cast Exception when trying to de-serialize back from JSONData object
[英]Unity LitJson.JsonData exception on cast in foreach loop
我的以下代碼段的foreach
語句中出現以下異常:
exception: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)
{
...
}
}
LitJson.JsonData
類聲明為:
public class JsonData : IJsonWrapper, IEquatable<JsonData>
IJsonWrapper
依次從這兩個接口派生: System.Collections.IList
和System.Collections.Specialized.IOrderedDictionary
。
請注意,這兩個都是非通用集合版本。 枚舉時,您不會得到KeyValuePair<>
作為結果。 相反,它將是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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.