Grails Json Apis Plugin

0 vote
Dependency:
compile ":json-apis:0.9"

 Documentation  Source  Issues

Summary

Allows developers to declaratively define various JSON serialization profiles and use them to marshall Grails domain classes at different levels of detail or from different starting points in the object graph.

Installation

grails install-plugin json-apis

Description

The goal of this plugin is to help convert Grails domain classes into various JSON representations needed in different parts of your web application or to support various API versions.

Features

  • Allows you to declare multiple named JSON configurations for different use cases
  • Configuration is very straightforward: all that is required is to mark domain class properties with a single annotation naming the configurations under which that property should be included in the serialized JSON object
  • Works for collections as well as belongsTo properties
  • Enables developers to avoid the circular object reference problem elegantly by defining appopriate namespaces - this way it is possible to start the serialization either in a parent or child entity, depending on the use case
  • Works for objects serialized inside a JSON Builder
  • Uses the Grails' ObjectMarshaller mechanism under the hood

Example

import grails.plugins.jsonapis.JsonApi

class User {

static hasMany = [ pets: Pet ]

@JsonApi String screenName

@JsonApi('userSettings') String email

@JsonApi(['userSettings', 'detailedInformation', 'social']) String twitterUsername

@JsonApi(['detailedInformation', 'userSettings']) Set pets

String neverGetsSerialized

@JsonApi('detailedInformation') Integer getNumberOfTicklyAnimals() { pets.count { it.likesTickling } } }

JSON.use("detailedInformation")
render userInstance as JSON

See the (short) documentation for details and more examples.

Future plans

  • Detect circular APIs and display a warning on startup, perhaps disable them entirely
  • Detect API changes without restarting the app in development mode
  • Add a script/controller that would document the registered APIs in one or more formats
  • Read the domain class annotations and produce configurations for those 3rd party JSON renderers which currently seem to perform better than the native Grails implementation