Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: protobuf from string

I'm using proto3 with grpc, and I'm looking at a more efficient way of creating a protobuf message without using a builder and populating it.

If I have a string (from Message.toString()), can I recreate the message with the string?

If I have a message type

message TestMessage {
    bool status = 1;
    uint64 created = 2;
    TestNested submessage = 3;


    message TestNested {
        int32 messageNumber = 1;
        Entry entry = 2;
    }

    message Entry {
        int32 id = 1;
        EntryType entryType = 2;
    }

    enum EntryType {
        DEFAULT_ENTRY = 0;
        OTHER_ENTRY = 1;
    }
}

and the below output:

status: true
created: 1534240073415
submessage {
  messageNumber: 3
  entry{
    id: 47957
    entryType: DEFAULT_ENTRY
  }
}

How can I create the TestMessage? I've looked at the JavaDoc to see if there's a parseFrom() method that takes in a string, but I'm not winning.

like image 818
nevi_me Avatar asked Sep 03 '18 14:09

nevi_me


1 Answers

I was looking for the TextFormat parser. The format that Message.toString() prints is the TextFormat representation.

To convert back to a protobuf message, I did the below:

TestMessage testMessage = new TestMessage.newBuilder();

CharSequence myText = "status: true\n ...";

com.google.protobuf.TextFormat.getParser().merge(myText, testMessage);
like image 122
nevi_me Avatar answered Oct 14 '22 14:10

nevi_me