标签:numerical key dynamic json c
我有一个json对象,我借助this答案将其转换为动态C#对象.它工作正常,但麻烦的是该对象具有数字键.例如,
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;
}
标签:numerical,key,dynamic,json,c 来源: https://codeday.me/bug/20191208/2090203.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。