protobuf 生成的类 转 json字符串

x33g5p2x  于3个月前 转载在 其他  
字(1.0k)|赞(0)|评价(0)|浏览(88)

背景

项目中rpc接口定义的类是使用protobuf定义的,然后会自动生成对应的类,但是打印的时候会换行,所以看看怎么解决这个问题

例子

public static void main(String[] args) {
        Test test = Test.newBuilder().setA("a").setB("b").setC("c").build();
        System.out.println(test);
    }

输出:
a: "a"
b: "b"
c: "c"

可以看到有换行

方案

<!--protobuf与json互转-->
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java-util</artifactId>
    <version>3.23.1</version>
</dependency>

public static String writeValueAsString(MessageOrBuilder message) {
    try {
        return JsonFormat.printer()
                .omittingInsignificantWhitespace() //去掉换行
                .print(message);
    } catch (Exception e) {
        log.error("print error, message={}, msg={}", message, e.getMessage(), e);
    }
    return StringUtils.EMPTY;
}

public static void main(String[] args) {
    Test test = Test.newBuilder().setA("a").setB("b").setC("c").build();
    System.out.println(writeValueAsString(test));
}
输出:
{"a":"a","b":"b","c":"c"}

相关文章