例如
{"orderNumber":"S301020000","customerFirstName":"ke ČECHA ","customerLastName":"张科","orderStatus":"PENDING_FULFILLMENT_REQUEST","orderSubmittedDate":"May 13, 2015 1:41:28 PM"}
如何获取上面 json 字符串中的重音字符(如“Č”)并在 java 中对其进行转义
请给出这个问题的一些背景信息,请检查我的这个问题 Ajax unescape response text from java servlet not working properly
抱歉我的英语:)
最佳答案
您应该转义所有大于 0x7F
的字符。您可以使用 .charAt(index)
方法循环遍历字符串的字符。对于每个需要转义的字符 ch
,将其替换为:
String hexDigits = Integer.toHexString(ch).toUpperCase();
String escapedCh = "\\u" + "0000".substring(hexDigits.length) + hexDigits;
我认为您不需要在 JavaScript 中对它们进行转义,因为 JavaScript 支持字符串文字中的转义字符,因此您应该能够按照服务器返回的方式处理字符串。我猜您将使用 JSON.parse() 将返回的 JSON 字符串转换为 JavaScript 对象,like this .
这是一个完整的函数:
public static escapeJavaScript(String source)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < source.length(); i++)
{
char ch = source.charAt(i);
if (ch > 0x7F)
{
String hexDigits = Integer.toHexString(ch).toUpperCase();
String escapedCh = "\\u" + "0000".substring(hexDigits.length) + hexDigits;
result.append(escapedCh);
}
else
{
result.append(ch);
}
}
return result.toString();
}
关于java 如何转义字符串中的重音字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30251071/