Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic json object with numerical keys

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": {...}}}";  

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.

like image 650
Tror Avatar asked Sep 10 '26 21:09

Tror


1 Answers

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;
        }
like image 116
Yet Another Geek Avatar answered Sep 12 '26 12:09

Yet Another Geek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!