如何(base64)将 protobuf 编码为字符串

How to (base64) encode a protobuf as a String

我有一个 protobuf 并想在 base64(或其他文本编码)中对其二进制表示进行编码,以便通过文本协议进行传输。最干净的方法是什么?

最简单的选择是 convert your proto to a byte[] and then use Guava's BaseEncoding class 将这些字节编码为 base64 字符串:

String asBase64 = BaseEncoding.base64().encode(proto.toByteArray());

这是最直接的,但还有许多其他大致等效的机制。例如,如果你想将编码数据写入文件或其他可写资源,你可以将其写入 BaseEncoding.encodingStream():

返回的 OutputStream
proto.writeTo(BaseEncoding.base64().encodingStream(fileWriter));

从 Java 8 开始还有 java.util.Base64, if you're not using Guava. See encode(byte[]) and wrap(OutputStream)


正如 Jon Skeet 所提到的,proto3 可以 map to and from JSON 如果您不明确需要以二进制格式传输数据(当然,您正在使用 proto3)。