这似乎有效。
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) 快得多。