Writing JSON APIs : Part II – Creating JSON Named Configs to Control What You Render

29 / Dec / 2011 by Vivek Krishna 0 comments

In the 1st part of the series, we looked at how to secure our application with Spring Security Basic Authentication and modifying the JSON Marshaller. However, it could often be the case that the same set of fields shouldn’t be returned on every JSON response.

For example, we could very well have a summary JSON for Book, which just returns the id and name of the Book, ignoring the other details like ISBN, genre etc. A real life example would be a Product’s complete details when returning JSON for its show view, while returning just the id, name and price for its view in a shopping cart.

In addition to that, we could choose, not to override the default JSON Marshallers provided by Grails so that the standard rendering method is not tampered.

Grails provides an excellent solution called “Named Configurations” which comes to our aid here. That, combined with some minor modifications on our CustomDomainClassJSONMarshaller can help us achieve this.

1. Add a static Map to the domain class, probably jsonProperties :

This property will hold the group name as key and the list of properties to be included as values.


//Book.groovy

static jsonProperties = [summary:['name']] //summary is the group name

2. Update the CustomDomainClassJSONMarshaller to have a property jsonPropertyGroup :

String jsonPropertyGroup
public CustomDomainClassJSONMarshaller(boolean includeVersion, GrailsApplication application, String jsonPropertyGroup = "") {
      this(includeVersion, new DefaultProxyHandler(), application, jsonPropertyGroup);
}
public CustomDomainClassJSONMarshaller(boolean includeVersion, ProxyHandler proxyHandler, GrailsApplication application, String jsonPropertyGroup) {
      this.includeVersion = includeVersion;
      this.proxyHandler = proxyHandler;
      this.application = application;
      this.jsonPropertyGroup = jsonPropertyGroup
}

3. Update the custom marshaller registrations to create Named Configs :

This method needs updation for two reasons

  • Calling the newly created constructors
  • API changes in grails 2.0

For creating a named config “summary”, we need to write something like


JSON.createNamedConfig(JSONConstants.SUMMARY_JSON_MARSHALLER_GROUP){
     it.registerObjectMarshaller(new CustomDomainClassJSONMarshaller(false, grailsApplication, "summary"), 2)
}

4. Using the newly registered named configs from within the controller:

This is the final step. We can use the named config with a static method JSON.use(), which takes in the configuration’s name and a closure inside which we will call the render <XYZ> as JSON method


JSON.use("summary"){
     render Book.list() as JSON
}

I have updated the example application to grails 2.0 and added an example to this approach.

Grails never ceases to amaze me. :)

FOUND THIS USEFUL? SHARE IT

Leave a comment -