Create a JSON structural type from an example object

Procedure

  1. Generate an example JSON object that contains every possible property. Every property must be non-empty and have the correct JSON type: a String, a number, an array, or another object.
    For example:
    {
      "Name": "Andy Applegate",
      "Age": 29,
      "Address": {
        "Number": 123,
        "Street": "Main St",
        "City": "Foster City",
        "State": "CA"
      },
      "Hobby": [
        {
          "Category": "Sport",
          "Name": "Baseball"
        },
        {
          "Category": "Recreation",
          "Name": "Hiking"
        }
      ]
    }
  2. Upload that data as a file on a web server.
  3. In the Gosu Scratchpad, use the java.net.URL Gosu enhancement property JsonContent.
    var personUrl = new URL( "http://URL-path/file-name.json" )
  4. In the Gosu Scratchpad, take the result of the previous step and call the toStructure method and pass the following two arguments:
    • A name of your new structural type, as a String
    • A Boolean that represents whether the structural type is mutable. If you want only property getters but not setters, pass the value false. If you want property getters and setters, pass the value true.
    For example:
    var personUrl = new URL( "http://gosu-lang.github.io/data/person.json" )
    var person: Dynamic = personUrl.JsonContent
    var sj = person.toStructure( "Person", false ) 
  5. Print the result, which contains Gosu code for a new structural type based on the structure of your example JSON data.
    For example:
    print(sj)
    The output looks like the following:
    structure Person {
      static function fromJson( jsonText: String ): Person {
        return gw.lang.reflect.json.Json.fromJson( jsonText ) as Person
      }
      static function fromJsonUrl( url: String ): Person {
        return new java.net.URL( url ).JsonContent
      }
      static function fromJsonUrl( url: java.net.URL ): Person {
        return url.JsonContent
      }
      static function fromJsonFile( file: java.io.File ) : Person {
        return fromJsonUrl( file.toURI().toURL() )
      }
      property get Address(): Address
      property get Hobby(): List<Hobby>
      property get Age(): Integer
      property get Name(): String
      structure Address {
        property get Number(): Integer
        property get State(): String
        property get Street(): String
        property get City(): String
      }
      structure Hobby {
        property get Category(): String
        property get Name(): String
      }
    }
  6. To use the structural type in other types, you can do either of the following:
    • To make a top-level type, copy and paste the structural type declaration into a new .gs file within your desired package.
    • To make an inner type, similar to an inner class in Gosu or Java, copy and paste the structural type declaration into a class declaration.

What to do next

See also