我有一个 json 对象,在以下命令的帮助下将其转换为动态 C# 对象this https://stackoverflow.com/questions/3142495/deserialize-json-into-c-dynamic-object/3806407#3806407回答。它工作得很好,但问题是这个对象有数字键。例如,
var jsStr = "{address:{"100": {...}}}";
所以我不能写
dynObj.address.100
而且,据我所知,我不能使用索引器来获取这个对象,如下所示
dynObj.address["100"]
请向我解释一下如何才能使其正常工作。
据我从源代码中可以看到,他通过私有字典解析属性,因此您必须使用反射来访问字典键,或者稍微修改他的代码,以便 DynamicJSONObject 中的 TryGetMember 如下(并使用 __numeric__ 来获取密钥,例如 data.address.__numeric__100,然后避免使用 __numeric__ 作为密钥):
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var name = binder.Name;
//Code to check if key is of form __numeric__<number> so that numeric keys can be accessed
if (binder != null && binder.Name != null && binder.Name.StartsWith("__numeric__"))
{
name = binder.Name.Substring(11);
}
if (!_dictionary.TryGetValue(name, out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}
var dictionary = result as IDictionary<string, object>;
if (dictionary != null)
{
result = new DynamicJsonObject(dictionary);
return true;
}
var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
if (arrayList[0] is IDictionary<string, object>)
result = new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)));
else
result = new List<object>(arrayList.Cast<object>());
}
return true;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)