美文网首页
protobuf与json相互转换的方法

protobuf与json相互转换的方法

作者: Yobhel | 来源:发表于2020-09-28 21:29 被阅读0次

google的protobuf对象转json,不能直接使用FastJson之类的工具进行转换,原因是protobuf生成对象的get方法,返回的类型有byte[],而只有String类型可以作为json的key。google有提供专门的架包,方便protobuf与json之间相互转换。方法如下:

  • 1、添加转换用的maven依赖:
<dependency>
    <groupId>com.googlecode.protobuf-java-format</groupId>
    <artifactId>protobuf-java-format</artifactId>
    <version>1.2</version>
</dependency>
  • 2、protobuf转json的方法
  Message.Builder message = Message.newBuilder();
  String json = JsonFormat.printToString(message.build());
  • 3、json转protobuf的方法
    try {
        JsonFormat.merge(json, message);
    } catch (ParseException e) {
        e.printStackTrace();
    }

相关文章

网友评论

      本文标题:protobuf与json相互转换的方法

      本文链接:https://www.haomeiwen.com/subject/rxvjuktx.html