Last active
December 14, 2015 20:39
-
-
Save beckje01/5145266 to your computer and use it in GitHub Desktop.
Example ExposedGSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.