我有一个 json 对象,我在 this 的帮助下将其转换为动态 C# 对象回答。它工作得很好,但问题是这个对象有数字键。例如,
var jsStr = "{address:{"100": {...}}}";
所以我不会写
dynObj.address.100
而且,据我所知,我不能像这样使用索引器来获取这个对象
dynObj.address["100"]
请向我解释如何使它正常工作。
最佳答案
据我看源码他是通过私有(private)字典来解析属性的,所以你得用反射来访问字典键,或者稍微修改一下他的代码,让DynamicJSONObject中的TryGetMember是下面的(和使用 __numeric__ 获取 key ,例如 data.address.__numeric__100,然后避免使用 __numeric__ 作为 key ):
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;
}
关于c# - 带有数字键的动态 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6387623/