-
Notifications
You must be signed in to change notification settings - Fork 297
Classes: JSONNode.this[string aKey]
public virtual JSONNode this[string aKey] { get; set; }
This indexer is used to access the members of a JSONObject. If a certain key does not exist in the internal dictionary it will be created when you set a value to this indexer. Trying to read a non-existing key will return a new instance of the JSONLazyCreatore class.
While it is possible to use this indexer to test if a certain key exists if(node["some key"])
it's not recommended since it will create a new JSONLazyCreator instance each time. It's better to use if(node.HasKey("some key"))
or if you want to read a key conditionally and provide a default value otherwise, use var res = node.GetValueOrDefault("some key", yourDefaultValue);
Note that the default value is a JSONNode and GetValueOrDefault will return a JSONNode. If you pass for example a string as default value when the method is called you will implicitly create a new JSONString. So be careful in tight loops with things like:
int val = node.GetValueOrDefault("some key", 42);
This will implicitly do this:
int val = node.GetValueOrDefault("some key", new JSONNumber(42));
When this indexer is used on an JSONArray, setting the indexer will behave like a call to Add regardless of the actual key used node["doesn't matter"] = val;
would just do node.Add(val);
. Reading that indexer for an array will always return a JSONLazyCreator which in turn might add an element to the array. So if node is a JSONArray this line:
node["foobar"]["some key"] = 5;
Will just add a new object to the end of the array.