【发布时间】:2018-04-12 10:10:58
【问题描述】:
我有一个如下所示的字符串:
{\x22documentReferer\x22:\x22http:\x5C/\x5C/pikabu.ru\x5C/freshitems.php\x22}
如何将其转换为可读的 JSON?
我发现了不同的慢速解决方案,例如 here with regEx
已经试过了:
URL.decode
StringEscapeUtils
JSON.parse // from different libraries
例如,python 有简单的解决方案,例如从'string_escape' 解码
链接的可能重复项适用于 Python,我的问题是关于 Java 或 Scala
我现在使用的工作但也很慢的解决方案来自here:
def unescape(oldstr: String): String = {
val newstr = new StringBuilder(oldstr.length)
var saw_backslash = false
var i = 0
while (i < oldstr.length) {
{
val cp = oldstr.codePointAt(i)
if (!saw_backslash) {
if (cp == '\\') saw_backslash = true
else newstr.append(cp.toChar)
} else {
if (cp == '\\') {
saw_backslash = false
newstr.append('\\')
newstr.append('\\')
} else {
if (cp == 'x') {
if (i + 2 > oldstr.length) die("string too short for \\x escape")
i += 1
var value = 0
try
value = Integer.parseInt(oldstr.substring(i, i + 2), 16)
catch {
case nfe: NumberFormatException =>
die("invalid hex value for \\x escape")
}
newstr.append(value.toChar)
i += 1
}
else {
newstr.append('\\')
newstr.append(cp.toChar)
}
saw_backslash = false
}
}
}
i += 1
}
if (saw_backslash) newstr.append('\\')
newstr.toString
}
private def die(msg: String) {
throw new IllegalArgumentException(msg)
}
【问题讨论】:
-
你有没有尝试过?在我看来,没有研究!
-
@Prashant 在你看来。我已经尝试过在描述和其他方面链接的慢速
-
您为 Python 链接了问题,我询问了 Scala 的 Java 解决方案。你读过这个问题吗?
-
@Prashant 请解释链接重复项
-
关于 Python 和 OP 的可能重复链接问题表明他或她已尝试使用该答案中的指导但无济于事。应该保持打开状态。
标签: java json scala decode utf