我有一个用例,其中我有一个预转义的有效字符串作为 JsonElement 返回。但是,内部使用 JsonWriter 的 JsonElement 会解析字符串以尝试进行字符串转义/字符替换。
私有(private) void string() 方法
出于性能原因,我想避免这样做,因为我的 String 元素是预转义的。
我搜索了一下,发现这个用例很相似: https://code.google.com/p/google-gson/issues/detail?id=239
虽然上述链接中的解决方案适用于 gson1.5,但 Escaper 类已在最新的 gson (2.2.2) 中删除。
我如何扩展 JsonElement(或其内部的 JsonWriter),从而避免特定类型的 JsonWriter 字符串替换开销?
最佳答案
这似乎可行。
OutputStream rawStream = ...
JsonWriter writer = new JsonWriter(new OutputStreamWriter(rawStream, "UTF-8"));
... /* normal gson/json usage */
// about to write object including a base 64 big byte[]
/* don't using binding API for images, too big, too slow */
String b64 = Base64.encodeToString(blob, Base64.NO_WRAP);
writer.beginObject();
writer.flush();
/* gson.JsonWriter doesn't understand the string is b64 encoded,
and hence doesn't need escaping, so lets use an ASCII encoder
for a little while
*/
OutputStreamWriter asciiWriter = new OutputStreamWriter(rawStream, "ASCII");
asciiWriter.write(
String.format("\"id\": \"%d\", \"raw\": \"", param.id)
);
asciiWriter.write(b64);
asciiWriter.write("\" ");
asciiWriter.flush();
writer.endObject();
虽然不是“在 API 中”,但鉴于此应该会继续工作
- 开始一个 JSON 对象是一个已知点(例如,在 { 之后没有要保留的“状态”)
- 结束一个空的JSON对象也是一个已知点('可以只放大括号})
- 这反过来意味着同时将有效的 JSON 写入 ascii 不需要影响 JSON 编写器的状态。
请注意,我已经对此进行了测试,它有效,并且比使用 JsonWriter.value(String value) 快得多。
关于java - Gson 2.2.2 Json 为 JsonElement 自定义 JsonWriter 以避免转义字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15486137/