【发布时间】:2014-09-25 20:34:28
【问题描述】:
我正在尝试返回带有 可能 包含双引号的文本的 JSON 响应。例如
"12.10 On-Going Submission of ""Made Up"" Samples."
我已经使用
转义了双引号StringEscapeUtils.escapeJava(artifact.text);
完美地转义了引号
\"12.10 On-Going Submission of \"\"Made Up\"\" Samples.\"
但是 JSON 响应被截断了
{
"documentName":"ICENSE AGREEMENT6",
"listOfArtifacts":[
{
"type":"Clause",
"artifacts":[
{
"documentId":6951,
"documentName":"ICENSE AGREEMENT6",
"artifactId":7029,
"text":"\\\"12.10 On-Going Submission o\\\"\\\""
这是一个 REST 服务,我在其中手动返回了 JSON。 (这不是完整的代码,但我希望你能明白。最终结果呈现为 JSON)
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 (artifacts) {
def k = StringEscapeUtils.escapeJava(artifact.text);
def artifactToAdd = [
documentId: artifact.documentId,
documentName: artifact.document.docName,
artifactId: artifact.id,
//text: k,
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
}
所以即使转义是正确的,为什么 JSON 会被截断?同样在控制台上我收到一个错误:
2014-09-25 14:55:07,555 [http-bio-8080-exec-1] ERROR errors.GrailsExceptionResolver - StringIndexOutOfBoundsException occurred when processing request: [GET] /artifact - parameters:
documentName: ICENSE AGREEMENT6
String index out of range: -25. Stacktrace follows:
Message: String index out of range: -25
Line | Method
->> 1911 | substring in java.lang.String
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 1946 | subSequence in ''
| 1042 | append . . . . in java.io.PrintWriter
| 56 | append in ''
| 180 | value . . . . in grails.converters.JSON
| 162 | convertAnother in ''
| 202 | value . . . . in ''
| 162 | convertAnother in ''
| 202 | value . . . . in ''
| 162 | convertAnother in ''
| 202 | value . . . . in ''
| 134 | render in ''
| 150 | render . . . . in ''
| 328 | $tt__index in com.thomsonreuters.ald.aeandsdx.ArtifactController
| 198 | doFilter . . . in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . . . in java.lang.Thread
【问题讨论】: