Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JsonFormat.printer().print() work?

I have a very simple proto:

message ChargeCardResponse
{
    bool success = 1;
}

When I'm trying to parse it to String I get a very strange output from the JsonFormat.printer().print() which depends on the success value.

ChargeCardResponse.Builder builder = ChargeCardResponse.newBuilder();
System.out.println(JsonFormat.printer().print(builder.setSuccess(true).build()));

Output: { "success": true }

ChargeCardResponse.Builder builder2 = ChargeCardResponse.newBuilder();
System.out.println(JsonFormat.printer().print(builder2.setSuccess(false).build()));

Output: {}

So if I give false value to the printer with the success property it can't make the JSON format. What am I doing wrong? Is there anybody who can confirm it?

like image 684
kbenda Avatar asked Mar 22 '18 16:03

kbenda


1 Answers

The thing is that setting success to "false" is equivalent to leaving the default "false" value intact.

JsonPrinter omits default proto values, unless that option it turned off:

https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/util/JsonFormat.Printer#includingDefaultValueFields--

This should work, I think:

ChargeCardResponse.Builder builder2 = ChargeCardResponse.newBuilder();
System.out.println(JsonFormat.printer().includingDefaultValueFields().print(builder2.setSuccess(false).build()));
like image 129
Piotr Avatar answered Nov 02 '22 13:11

Piotr