Skip to content

Instantly share code, notes, and snippets.

@beckje01
Last active December 14, 2015 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beckje01/5145266 to your computer and use it in GitHub Desktop.
Save beckje01/5145266 to your computer and use it in GitHub Desktop.
Example ExposedGSON
package com.reachlocal.product.gson
import com.google.gson.GsonBuilder
import grails.plugin.gson.converters.GSON
import org.codehaus.groovy.grails.commons.ApplicationHolder
class ExposedGSON extends GSON {
@Lazy
private GsonBuilder gsonBuilder = {
def applicationContext = ApplicationHolder.application.mainContext
applicationContext.getBean('gsonBuilder', GsonBuilder)
}()
private String version = null
private target
ExposedGSON(def version = null) {
this.version = version
}
@Override
void setTarget(target){
super.setTarget(target)
this.target = target
}
@Override
void render(Writer out) {
try {
def builder = gsonBuilder
if (version && version.isDouble()) {
builder = builder.setVersion(version as double)
}
builder.excludeFieldsWithoutExposeAnnotation().create().toJson(target, out)
} finally {
out.flush()
out.close()
}
}
}
package com.example.gson
import com.google.gson.GsonBuilder
import grails.plugin.gson.converters.GSON
import org.codehaus.groovy.grails.commons.ApplicationHolder
class ExposedGSON extends GSON {
@Lazy
private GsonBuilder gsonBuilder = {
def applicationContext = ApplicationHolder.application.mainContext
applicationContext.getBean('gsonBuilder', GsonBuilder)
}()
private target
ExposedGSON() {}
ExposedGSON(target) {
setTarget(target)
}
@Override
void setTarget(target){
super.setTarget(target)
this.target = target
}
@Override
void render(Writer out) {
try {
gsonBuilder.excludeFieldsWithoutExposeAnnotation().create().toJson(target, out)
} finally {
out.flush()
out.close()
}
}
}
@robfletcher
Copy link

I was thinking that rather than needing to change the syntax you use to convert to JSON you could just register a variant of the GrailsDomainSerializer class in the application context. Since that can be done on a class-by-class basis it would allow for using the @Expose style with some classes and the regular style with others.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment