Search code examples
javaprotocol-buffersprotobuf-c

How do I know what the json for a protobuff should be formatted like?


I'm new to protobuf's, and I'd like to save some protobuf's to json format, and know what the full format for the protobuf is. I've tried just creating an empty instance of the protobuf, and saving it to json, but that only gives me an empty json object, {}.

If I fill in a value for a property, and serialize that, I get the property in the json, which is great, but I don't want to have to do this for all the properties of each protobuf I want to do this for.

Is there a way for me to see the full json format for a protobuf without supplying a value for every field?

Notes
  • I'm using Google's protobuf library in Java, and can serialize and deserialize my objects, I'm just not sure how to write the json for a particular object.
  • I've reviewed this stackoverflow question for info, but found nothing that helped.

Solution

  • Yes, the JSON formatting for proto3 is documented.

    Alternatively, to see an example without changing the defaults, you could specify the includingDefaultValueFields when printing:

    String json = JsonFormat.printer().includingDefaultValueFields().print(message);
    

    (That should at least work for primitives; I suspect it will print null for nested messages if they haven't been initialized.)