JSON APIs for URLs
Because JSON data often comes from internet
requests, Gosu adds an enhancement property named JsonContent to the standard Java
class java.net.URL to
simplify your JSON integrations. If the URL object is an HTTP URL, accessing
the JsonContent property
fetches the JSON content by running the HTTP GET method. If the content of
the URL object is a JSON
document, this property provides a JSON object that reflects the structure
and data in that document.
Parsing JSON from a URL
To get JSON data from a URL, you first create
an instance of java.net.URL
using the URL as the argument. Next, you get the JsonContent property on an instance
of URL. The JsonContent property getter performs
several complex tasks:
- The getter makes the HTTP or other URL request from the internet and gets the result as text.
- The getter parses the JSON text into a Bindings object using the static method gw.lang.reflect.json.Json.fromJson(urlRequestString).
- The getter coerces this Bindings object to the type
dynamic.Dynamicbefore returning the object. Because the type is dynamic, you can use type inference when assigning the result to a variable.
For example, run the following code in the Gosu Scratchpad:
// Create a URL
var personUrl = new URL( "http://gosu-lang.github.io/data/person.json" )
// Access the URL, parse the JSON text content to a Bindings object, return as dynamic.Dynamic.
var person = personUrl.JsonContent
// Parse the dynamic object using a natural Gosu syntax
print( person.Name )
Note that any JSON property that contains an array becomes a standard Java list, which you can use with array index syntax or loops.
See also
