编程语言
首页 > 编程语言> > C#-具有数字键的动态json对象

C#-具有数字键的动态json对象

作者:互联网

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