Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol buffer `ParseFromString` in Java for parsing text format?

Is ParseFromString available in Java for protocol buffers?

The C++ version has it: here

like image 675
Tianyang Li Avatar asked Mar 06 '15 00:03

Tianyang Li


People also ask

Is Protobuf text or binary?

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.

What format is 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.

What is protocol buffers Java?

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).


2 Answers

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.

like image 129
P Marecki Avatar answered Sep 28 '22 17:09

P Marecki


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);
}
like image 43
user253751 Avatar answered Sep 28 '22 17:09

user253751