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

 

1、添加转换用的maven依赖:

1     <dependency>
2         <groupId>com.googlecode.protobuf-java-format</groupId>
3         <artifactId>protobuf-java-format</artifactId>
4         <version>1.2</version>
5     </dependency>    

 

2、protobuf转json的方法

1     // protobuf 转 json
2     Message.Builder message = Message.newBuilder();
3     String json = JsonFormat.printToString(message.build());

 

3、json转protobuf的方法

1     //json 转 protobuf
2     try {
3         JsonFormat.merge(json, message);
4     } catch (ParseException e) {
5         e.printStackTrace();
6     }

 

相关文章:

  • 2021-09-26
  • 2021-09-28
  • 2021-06-12
  • 2021-12-28
  • 2022-12-23
  • 2022-12-23
  • 2021-11-21
  • 2021-06-24
猜你喜欢
  • 2022-12-23
  • 2021-11-14
  • 2022-12-23
  • 2022-01-12
  • 2022-01-02
  • 2021-12-23
相关资源
相似解决方案