简体   繁体   English

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

[英]How to (base64) encode a protobuf as a String

I have a protobuf and want to encode its binary representation in base64 (or another textual encoding) for transmission over a text protocol.我有一个 protobuf 并且想用 base64(或其他文本编码)对其二进制表示进行编码,以便通过文本协议进行传输。 What's the cleanest way to do that?最干净的方法是什么?

The easiest option is to convert your proto to a byte[] and then use Guava 's BaseEncoding class to encode those bytes as a base64 string:最简单的选择是将您的 proto 转换为byte[] ,然后使用GuavaBaseEncoding类将这些字节编码为 base64 字符串:

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

This is the most straightforward, but there are a number of other roughly equivalent mechanisms.这是最直接的,但还有许多其他大致等效的机制。 For example if you want to write the encoded data to a file or other writable resource, you could write it to an OutputStream returned by BaseEncoding.encodingStream() :例如,如果要将编码数据写入文件或其他可写资源,则可以将其写入BaseEncoding.encodingStream()返回的OutputStream

proto.writeTo(BaseEncoding.base64().encodingStream(fileWriter));

As of Java 8 there's alsojava.util.Base64 , if you're not using Guava.从 Java 8 开始,如果您不使用 Guava,还有java.util.Base64 See encode(byte[]) and wrap(OutputStream) .请参阅encode(byte[])wrap(OutputStream)


As Jon Skeet mentioned, proto3 canmap to and from JSON if you don't explicitly need to transmit the data in binary format (and you're using proto3, of course).正如 Jon Skeet 所提到的,如果您不需要以二进制格式传输数据(当然,您正在使用 proto3),proto3 可以映射到 JSON 和从 JSON 映射

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM