Is ParseFromString
available in Java for protocol buffers?
The C++ version has it: here
Is ParseFromString
available in Java for protocol buffers?
The C++ version has it: here
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);
}
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
.