使用jetty-util-ajax包中的JSON.toString()
方法时是否可以转义 UTF-8 字符?
我知道该程序包可能是一个内部库,但直到现在它在一个 servlet 中对我来说效果很好,其中包括通过 FCM(Firebase 云消息传递)和 ADM(亚马逊设备消息传递)向手机发送推送通知的任务。
然而,我的问题是 ADM 不接受任何 UTF-8 字符(在我的情况下是西里尔字母)并且可重复地失败并出现相当 误导性的错误消息(亚马逊在其所有错误消息中谈论 XML,而他们的 API 期望 JSON 数据被发布):
<SerializationException>
<Message>Could not parse XML</Message>
</SerializationException>
java.lang.IllegalStateException:
unknown char '<'(60) in |||<SerializationException>| <Message>Could
not parse XML</Message>|</SerializationException>||
那么在 Jetty 9.4.8.v20171121 中是否有可能对字符进行编码?
这是我的Java代码:
// this string is POSTed to ADM server
public String toAdmBody() {
Map<String, Object> root = new HashMap<>();
Map<String, String> data = new HashMap<>();
root.put("data", data);
data.put("body", mBody);
// ADM does not accept integers for some reason
data.put("gid", String.valueOf(mGid));
// HOW TO ENCODE UTF-8 CHARS TO \uXXXX HERE?
return JSON.toString(root);
}
private void postMessage(String registrationId, int uid, String jsonStr) {
mHttpClient.POST(String.format("https://api.amazon.com/messaging/registrations/%1$s/messages", registrationId))
.header(HttpHeader.ACCEPT, "application/json; charset=utf-8")
.header(HttpHeader.CONTENT_TYPE, "application/json; charset=utf-8")
.header(HttpHeader.AUTHORIZATION, "Bearer " + mAccessToken)
.header("X-Amzn-Type-Version", "com.amazon.device.messaging.ADMMessage@1.0")
.header("X-Amzn-Accept-Type", "com.amazon.device.messaging.ADMSendResult@1.0")
// add registrationID and notification body - for retrying after fetching token
.attribute("registrationId", registrationId)
.attribute("body", jsonStr)
.content(new StringContentProvider(jsonStr))
.send(mMessageListener);
}
在查看 Jetty 源代码JSON.java时,会发生一些解码(即从\uXXXX
UTF-8 字符):
case 'u':
char uc = (char)((TypeUtil.convertHexDigit((byte)source.next()) << 12)
+ (TypeUtil.convertHexDigit((byte)source.next()) << 8)
+ (TypeUtil.convertHexDigit((byte)source.next()) << 4)
+ (TypeUtil.convertHexDigit((byte)source.next())));
scratch[i++] = uc;
break;
但是如何做相反的事情呢?