Brad Parks
Brad Parks

Reputation: 72101

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

Upvotes: 0

Views: 2544

Answers (2)

Brad Parks
Brad Parks

Reputation: 72101

Not really any different that what was done in this answer to this question, but here's how I wrapped this up for my purposes - your results may vary, lol! This allowed me to have messages loaded from a json file, and deserialized into requests for grpc methods.

  import com.google.protobuf.InvalidProtocolBufferException;
  import com.google.protobuf.MessageOrBuilder;
  import com.google.protobuf.util.JsonFormat;

  /**
   * Convert gRPC message to Json string.
   *
   * @param messageOrBuilder the gRPC message
   * @return a Json string
   */
  public static String grpcMessageToJson(MessageOrBuilder messageOrBuilder) {
    String result = "";
    if (messageOrBuilder == null) {
      return result;
    }

    try {
      result = JsonFormat.printer().print(messageOrBuilder);
    } catch (InvalidProtocolBufferException e) {
      LOGGER.warn("Cannot serialize the gRPC message.", e);
    }

    return result;
  }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502106

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.)

Upvotes: 1

Related Questions