Skip to content
Jeff Scott Brown edited this page Aug 23, 2016 · 2 revisions

The Very Basics

Given a domain class like this:

class Widget {
    String name
    int width
    int height
}

And a .gson view like this:

model {
    Widget widget
}

json jsonapi.render(widget)

The resulting JSON should look something like this:

{"data":
  {"type":"widget",
   "id":"/domain/50/widgets/4",
   "attributes":
    {"height":7,
     "name":"One",
     "width":4
    }
  }
}

The id should default to the primary key for the entity (integer typically) but should be generated by a pluggable mechanism so custom id generators may be used. As an example, some applications may want to use the self link for the id.

The type should default to property name representation of the name of the class that the rendered object is an instance of.

A unit test like this should work:

package grails.plugin.json.view

import grails.persistence.Entity
import grails.plugin.json.view.test.JsonViewTest
import spock.lang.Specification

class JsonApiSpec extends Specification implements JsonViewTest {
    void setup() {
        mappingContext.addPersistentEntities(Widget)
    }

    void 'test simple case'() {
        when:
        def theWidget = new Widget(name: 'One', width: 4, height: 7).save()
        def result = render('''
import grails.plugin.json.view.Widget
model {
    Widget widget
}

json jsonapi.render(widget)
''', [widget: theWidget])

        then:
        result.jsonText == '''
{"data": {"type":"widget","id":"/domain/50/widgets/4","attributes":{"height":7,"name":"One","width":4}}}
'''
    }
}

@Entity
class Widget {
    String name
    int width
    int height
}
Clone this wiki locally