Created
April 26, 2014 23:15
-
-
Save axeda/11333652 to your computer and use it in GitHub Desktop.
Serializes custom object output into JSON or XML depending on the content type, just give it a map
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
import groovy.xml.StreamingMarkupBuilder | |
import net.sf.json.JSONObject | |
import groovy.xml.XmlUtil | |
class ReturnSerializer { | |
static final ReturnSerializer INSTANCE = new ReturnSerializer(); | |
final className = "com.axeda.innovation.ReturnSerializer" | |
ReturnSerializer() { | |
if(ReturnSerializer.INSTANCE != null) { | |
throw new RuntimeException("There is already an instance of the ReturnSerializer. Please use ReturnSerializer.INSTANCE to obtain an instance") | |
} | |
} | |
def createReturnMap(String contentType, String response) { | |
return ["Content-Type": contentType, "Content": response] | |
} | |
public String serializeReturn(contentType, map){ | |
if (contentType.contains("json")){ | |
return jsonReturn(map) | |
} | |
else if (contentType.contains("xml")) { | |
return xmlReturn(map) | |
} | |
else return createReturnMap("text/plain",map.inspect()) | |
} | |
def jsonReturn(map){ | |
map = [result: map] | |
return JSONObject.fromObject(map).toString(2) | |
} | |
def xmlReturn(map){ | |
def markupBuilder = new StreamingMarkupBuilder() | |
def xml = markupBuilder.bind { builder -> | |
Response { | |
Outcome { recursiveXMLBuilder builder, map } | |
} | |
} | |
return XmlUtil.serialize(xml) | |
} | |
/** | |
* recursiveXMLBuilder | |
* | |
* This is the most amazing function ever | |
* it builds xml dynamically, doesn't deal so well with lists | |
* @param builder StreamingMarkupBuilder the xml builder | |
* @param map Hashmap the map to serialize into xml | |
* @return | |
* @ | |
*/ | |
def recursiveXMLBuilder(builder, map){ | |
try { | |
map.each { k, v -> | |
if (v instanceof List){ | |
v.each{ entry -> | |
try { | |
builder."$k"{ | |
recursiveXMLBuilder(builder, entry) | |
} | |
} | |
catch(Exception e){ | |
builder."$k" entry | |
} | |
} | |
} | |
else if (v instanceof Map){ | |
builder."$k" { | |
v.each { entry -> | |
recursiveXMLBuilder(builder, entry) | |
} | |
} | |
} | |
else { | |
builder."$k" "$v" | |
} | |
} | |
} | |
catch(Exception e){ | |
builder.Error("Please provide a valid map for serialization.") | |
} | |
} | |
} | |
return ReturnSerializer.INSTANCE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment