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

喜夏-厌秋 提交于 2019-12-13 17:11:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!