0

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.
Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336

2 Answers2

1

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • It does seem to only work with primitives, but is better than nothing... thanks! and if you set an object, it dumps it and it's primitives, so very helpful. – Brad Parks Oct 28 '19 at 11:42
  • and if anyone else is wondering how to create an instance for any nested messages, there's a `.newBuilder()` method on each object that lets you create an instance – Brad Parks Oct 28 '19 at 12:21
0

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;
  }
Brad Parks
  • 66,836
  • 64
  • 257
  • 336