ScalaPB can convert protocol buffers to and from JSON, using json4s.
Make sure that you are using ScalaPB 0.5.x or later.
build.sbt add a dependency on
In your code, you can now convert to JSON:
Parse JSON back to a protocol buffer:
There are lower-level functions
fromJson() that convert from
protos to json4s's
Finally, in JsonFormat there are two implicit methods that instantiate
There are a few more options available to customize the format used to print
and parse JSON. To take advantage of that, instantiate
fromJson() as usual.
false): should fields that are set to their default value be included in the output.
false): by default, field names are mapped to lowerCamelCase and become JSON object keys. Setting this option to
truewould make the parser and the printer use the original field names as specified in the proto file (normally, in snake_case)
See the list of constructor paramerters here
In Protocol Buffers,
google.protobuf.Any is a type that embeds an arbitrary protobuf message. An
Any is represented as a message that contains a
typeUrl field that identifies the type, and a bytes field
value which contains the serialized contents of a message. In JSON, the message embedded in the
Any is serialized as usual, and there is a
@type key added to it to identify which message it is. The parser expects this
@type key to know which message it is. To accomplish this, all the expected embedded types need to be registered with a
TypeRegistry so the printer and parser know how to process the embedded message.
The following example is based on this proto.
Conversely, you can start from a JSON and parse it back to a
MyContainer that contains an