0

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

SriK
  • 1,011
  • 1
  • 15
  • 29
  • Possible duplicate of [Java: JSON -> Protobuf & back conversion](https://stackoverflow.com/questions/28545401/java-json-protobuf-back-conversion) – Ram Ghadiyaram Sep 06 '17 at 15:27

2 Answers2

1

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();
}
Moses
  • 611
  • 5
  • 20
0

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

SriK
  • 1,011
  • 1
  • 15
  • 29