用数字键动态JSON对象 [英] Dynamic json object with numerical keys

查看:164
本文介绍了用数字键动态JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我转换为动态C#与对象的这个回答。它工作得很好,但麻烦的是,这个对象有数字键。例如,

I have a json object which I converted to dynamic C# object with help of this answer. It works just fine, but trouble is that this object has numerical keys. For instance,

var jsStr = "{address:{"100": {...}}}";  



所以我不能WIRTE

So I can't wirte

dynObj.address.100  

和,因为我知道,我不能使用索引来获得这个对象是这样

And, as I know, I can't use indexers to get this object like this

dynObj.address["100"]  

请向我解释,我怎么能得到这个工作。

Please explain to me how I can get this working.

推荐答案

据我可以从他立志通过专用词典的属性的源代码中看到的,所以你必须使用反射来访问字典的键,或修改一行代码一下,让TryGetMember在DynamicJSONObject如下(并使用__numeric__拿到钥匙例如data.address .__ numeric__100,然后避免使用__numeric__作为键):

As far as I can see from the source code he resolves the properties through a private dictionary, so you have to use reflection to access the dictionary key, or modify his code a bit so that TryGetMember in DynamicJSONObject is the following (and use __numeric__ to get the key e.g. data.address.__numeric__100, and then avoid using __numeric__ as a 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;
        }

这篇关于用数字键动态JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆