Is ParseFromString
available in Java for protocol buffers?
The C++ version has it: here
Protobuf is a binary format, so working with it becomes tedious. Without an easy way to see what the message contained, I struggled to quickly implement the library and work with it. Specifically, I wanted a way to write configuration files that could be read into protobuf.
Protocol buffers, or Protobuf, is a binary format created by Google to serialize data between different services. Google made this protocol open source and now it provides support, out of the box, to the most common languages, like JavaScript, Java, C#, Ruby and others.
Protocol buffers are a combination of the definition language (created in . proto files), the code that the proto compiler generates to interface with data, language-specific runtime libraries, and the serialization format for data that is written to a file (or sent across a network connection).
For a message A
, method TextFormat.getParser().merge(str, builder);
does it. E.g.:
AOuterClass.A.Builder buildA = AOuterClass.A.newBuilder();
buildA.setName("Abra Kadabra");
buildA.addPrices(3.14);
buildA.addPrices(3.141592);
AOuterClass.A aaa = buildA.build();
String str = aaa.toString();
AOuterClass.A.Builder builder = AOuterClass.A.newBuilder();
///////////////////////////////////////////
TextFormat.getParser().merge(str, builder);
System.out.println(builder.build().equals(aaa)); //true
Tested with proto3
.
Here is the implementation of ParseFromString (note that TextFormat::ParseFromString
simply calls TextFormat::Parser::ParseFromString
on a new Parser
object):
bool TextFormat::Parser::Parse(io::ZeroCopyInputStream* input,
Message* output) {
output->Clear();
return Merge(input, output);
}
bool TextFormat::Parser::ParseFromString(const string& input,
Message* output) {
io::ArrayInputStream input_stream(input.data(), input.size());
return Parse(&input_stream, output);
}
You can see that Parse
simply clears the message, then calls Merge
. Although the Java implementation of Protocol Buffers doesn't have a Parse
method, you can easily implement it:
public static void parseFromString(CharSequence input, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException {
builder.clear();
TextFormat.merge(input, extensionRegistry, builder);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With