SriK
SriK

Reputation: 1121

How to convert Json representation of protobuf back to protobuf?

I am sending a json string that represents a protobuf and I want to convert it back to the protobuf message that I desire.

Upvotes: 0

Views: 6168

Answers (2)

Moses
Moses

Reputation: 711

Posting this to complete @Srik's answer.

You can use the JsonFormat class provided by Protobuf. Simply create a JsonParser object and parse the json string into a builder for the protobuf message. Below is a small snippet

private MyProtobufMessage parseJson(String jsonString) {
    JsonParser jsonParser = new JsonParser();
    MyProtobufMessage.Builder messageBuilder = MyProtobufMessage.newBuilder();

   JsonFormat.parser().usingTypeRegistry(TypeRegistry.getEmptyTypeRegistry()).merge(jsonString, messageBuilder);
    return message.build();
}

Upvotes: 1

SriK
SriK

Reputation: 1121

Found it right after i posted the question! You can use Gson to convert to and from json to protobuf.

Upvotes: 0

Related Questions