c# - 带有数字键的动态 json 对象

标签 c# json dynamic key numerical

我有一个 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/

相关文章:

javascript - 使用选择器再次调用 data() 时,动态创建元素并附加数据的 JQuery 不返回值?

javascript - 如何触发jquery点击事件动态生成列表

c# - 无法识别发送到 SQL Server 存储过程的参数

c# - 为什么 MonthCalendar 在 3rd 方应用程序中看起来不同?

java - Jackson 与泛型 JSON 无法构造 java.lang.Class 的实例

javascript - 如何更改 localStorage 项目中的单个值?

c - 调用进程的符号查找?

c# - MarshalAs(UnmanagedType.LPStr) - 这如何将 utf-8 字符串转换为 char*

c# - 将正则表达式转换为 htmlagilitypack

python - 在 Flask 中提供动态生成的文件