Convert between JSON and Protobuf
Last updated: October 18, 2022
1. Overview
In this tutorial, we’ll demonstrate how to convert from JSON to Protobuf and from Protobuf to JSON.
Protobuf is a free and open-source cross-platform data format used to serialize structured data.
2. Maven Dependency
To start, let’s create a Spring Boot project by including the protobuf-java-util dependency:
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
<version>3.21.5</version>
</dependency>
3. Convert JSON to Protobuf
We can convert JSON to a protobuf message by using JsonFormat. JsonFormat is a utility class to convert protobuf messages to/from JSON format. JsonFormat’s parser() creates a Parser, which uses the merge() method to parse JSON to protobuf message.
Let’s create a method that takes JSON and generates a protobuf message:
public static Message fromJson(String json) throws IOException {
Builder structBuilder = Struct.newBuilder();
JsonFormat.parser().ignoringUnknownFields().merge(json, structBuilder);
return structBuilder.build();
}
Let’s use the following sample JSON:
{
"boolean": true,
"color": "gold",
"object": {
"a": "b",
"c": "d"
},
"string": "Hello World"
}
Now, let’s write a simple test to validate the conversion from JSON to protobuf message:
@Test
public void givenJson_convertToProtobuf() throws IOException {
Message protobuf = ProtobufUtil.fromJson(jsonStr);
Assert.assertTrue(protobuf.toString().contains("key: \"boolean\""));
Assert.assertTrue(protobuf.toString().contains("string_value: \"Hello World\""));
}
4. Convert Protobuf to JSON
We can convert protobuf message to JSON by using JsonFormat‘s printer() method, which accepts protobuf as a MessageOrBuilder:
public static String toJson(MessageOrBuilder messageOrBuilder) throws IOException {
return JsonFormat.printer().print(messageOrBuilder);
}
Let’s write a simple test to validate the conversion from protobuf to JSON message:
@Test
public void givenProtobuf_convertToJson() throws IOException {
Message protobuf = ProtobufUtil.fromJson(jsonStr);
String json = ProtobufUtil.toJson(protobuf);
Assert.assertTrue(json.contains("\"boolean\": true"));
Assert.assertTrue(json.contains("\"string\": \"Hello World\""));
Assert.assertTrue(json.contains("\"color\": \"gold\""));
}
5. Conclusion
In this article, we’ve demonstrated how we can convert JSON to protobuf and vice versa.
As always, all code samples used in this tutorial are available over on GitHub.