分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

protobuf与json相互转换的方法

发布时间:2023-09-06 02:13责任编辑:赖小花关键词:jsjson

  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 转 json2 ????Message.Builder message = Message.newBuilder();3 ????String json = JsonFormat.printToString(message.build());

3、json转protobuf的方法

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

protobuf与json相互转换的方法

原文地址:https://www.cnblogs.com/pcheng/p/9586039.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved