Iterate over JObject?

Apr 26, 2009 at 7:13 PM
I'm trying to update some code (not originally mine) from Json.NET 1.1.1 to 3.5 b3. As far as I can tell, it looks like what was "JavaScriptObject" is now "JObject", but I'm getting an invalid cast exception when it gets iterated over:

        private void func(object jsonObject)
        {
            JObject javaScriptObject = jsonObject as JObject;
            if (javaScriptObject != null)
            {
                foreach (KeyValuePair<string, object> pair in javaScriptObject)
                {
                    // stuff
                }
            }
        }

The exception gets triggered by "KeyValuePair<string, object> pair". I can't find anywhere in the Json.NET docs information on what the correct type is.
Coordinator
Apr 27, 2009 at 9:58 AM
In 3.5 b3 you would iterate over it with a JProperty;

foreach (JProperty property in javaScriptObject)
{
  ...
}

From the property you would get the name and the value.

However, now that you've pointed this out to me I'm going to change it to be KeyValuePair<string, JToken> for the next version. You can either download and build from the latest source to get the new new way or stick with the version you have and use JProperty. The choice is yours :)