I have few strings like
"12.10 On-Going Submission of ""Made Up"" Samples."
10. PRODUCT STANDARDS; APPROVAL.
which I render as JSON in grails. The quotes and any other possible special characters are giving me trouble i.e they make the JSON invalid when returning a response from the REST service. How do I solve this? I have tried few things but nothing seems to work:
//text: java.net.URLEncoder.encode(artifact.text, "UTF-8"), //Loses the original format
//text : artifact.text.encodeAsJavaScript(), // give problem with ;
//text: artifact.text.encodeAsHTML(), // gives &qoute(not wanted) in the text instead of "
//text: StringEscapeUtils.escapeJava((String)artifact.text), //some error
// text : artifact.text // the json gets cut at the string
I have a similar question here to give you the idea of what exactly I am facing The code snippet :
def index() {
def document
def artifacts
def documentId
def documentName
def artifactType
def artifactStatus
def includeClassifications
def classifications
def mapOfAtifactTypes = [:]
def listOfArtifacts = []
def listOfClassifications = []
def rtnVal = [:]
documentId = params.documentId
documentName = params.documentName
try {
if (! rtnVal?.msg ) {
//if we dont' have a message yet it means we don't yet have a failure so we can continue
if (document){
rtnVal.documentName = document.docName
if (artifactType) {
artifacts = Artifact.findAllByDocumentAndArtifactType(document, artifactType)
}
else {
artifacts = Artifact.findAllByDocument(document)
}
} else {
artifacts = Artifact.list();
}
if (artifacts) {
def artifactToAdd = [
documentId: artifact.documentId,
documentName: artifact.document.docName,
artifactId: artifact.id,
//URLEncode so slashes and other control characters don't cause the rendered JSON to truncate
//TODO look up the proper way to encode text prior to JSON rendering
//text: java.net.URLEncoder.encode(artifact.text, "UTF-8"),
//text : artifact.text.encodeAsJavaScript(),
//text: artifact.text.encodeAsHTML(),
//text: StringEscapeUtils.escapeJava((String)artifact.text),
text: artifact.text.replace("\"","\\\""),
status: artifact.status ?: Artifact.ArtifactStatus.FOR_REVIEW.value,
hasClassification: listOfClassifications ? true : false
];
listOfArtifacts.add(artifactToAdd)
}
rtnVal.listOfArtifacts = []
mapOfAtifactTypes.each { entry ->
rtnVal.listOfArtifacts.add([
type: entry.key,
artifacts: entry.value
])
}
}
} catch (Exception e) {
e.printStackTrace()
rtnVal = [
status: "Bad request",
msg: e
]
render e
}
render rtnVal as JSON
}