Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. What's the cleanest way to do that?

like image 758
dimo414 Avatar asked Nov 18 '15 18:11

dimo414


1 Answers

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:

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():

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

As of Java 8 there's also java.util.Base64, if you're not using Guava. See encode(byte[]) and wrap(OutputStream).


As Jon Skeet mentioned, proto3 can map to and from JSON if you don't explicitly need to transmit the data in binary format (and you're using proto3, of course).

like image 110
dimo414 Avatar answered Nov 20 '22 20:11

dimo414