Dynamic access to JSON objects

You can convert a JSON document as String data to a dynamic Gosu object. You can navigate the result using property names and array index syntax in a natural way in Gosu.

Warning: Dynamic access to JSON data is powerful and convenient but is not type safe. For example, if you misspell a property name, the Gosu editor does not catch your error at compile time.

Parsing JSON from a String object

To convert JSON data to a dynamic object with Gosu property access, use the gw.lang.reflect.json.Json class. Call its fromJson method and pass the String data as an argument. The method is declared to return a Java object that implements the standard interface javax.script.Bindings. At run time, the return type javax.script.SimpleBindings, which implements the Bindings interface.

If you declare a variable of type Bindings or SimpleBindings, you can get properties from the object. However, you must use the awkward syntax of the get method and passing an attribute name as a quoted String object.

var jsonParsed = Json.fromJson(jsonText)
print("Name = " + jsonParsed.get("Name"))

This syntax is neither convenient nor natural Gosu syntax.

Instead, Gosu natively provides natural attribute-value programming access to the Bindings type if you declare a variable as the type dynamic.Dynamic. Use this approach to get properties by name with natural syntax. Any JSON property that contains an array becomes a standard Java list, which you can use with array index syntax, collection-related Gosu enhancements, or loop syntax.

For example, run the following code in the Gosu Scratchpad:

uses dynamic.Dynamic
uses gw.lang.reflect.json.Json

// For this example, note that a String literal must use \" to escape quote symbols
//
//    {"Name": "Andy Applegate", 
//      "Age": 29, 
//      "Hobbies": ["Swimming", "Hiking"]}
//
var jsonText = "{\"Name\": \"Andy Applegate\", \"Age\": 29, \"Hobbies\": [\"Swimming\", \"Hiking\" ] }"
var j : Dynamic = Json.fromJson(jsonText)

print("Name = " + j.Name)
print("Age = " + j.Age)
print ("Number of hobbies... " + j.Hobbies.size)
for (h in j.Hobbies) {
  print(" one hobby = " + h)
}

This code prints the following

Name = Andy Applegate
Age = 29
Number of hobbies... 2
 one hobby = Swimming
 one hobby = Hiking

See also