11

Is ParseFromString available in Java for protocol buffers?

The C++ version has it: here

2
  • I'm not familiar with Protocol Buffers, but does mergeing into a blank message do the same thing?
    – user20574
    Commented Mar 6, 2015 at 1:01
  • OK, I see there's something for Readable, thanks! Commented Mar 6, 2015 at 1:18

2 Answers 2

9

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.

2

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.