问题
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?
回答1:
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()));
来源:https://stackoverflow.com/questions/49433473/how-does-jsonformat-printer-print-work