1、json字符串和pb对象之间的转换:
1)pom.xml
<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.googlecode.protobuf-java-format</groupId> <artifactId>protobuf-java-format</artifactId> <version>1.2</version> </dependency>2)pb消息定义: option java_package = "com.abc.proto"; option java_outer_classname="HelloWordPB"; message HelloWord { optional int64 id = 1; optional string name = 2; repeated string recId = 3; }3)java代码: public class PBTest { public static void main(String[] args) { JSONObject jo = new JSONObject(); JSONArray ja = new JSONArray(); ja.add("1"); ja.add("2"); jo.put("id", 123456);//这里不能是字符串类型,否则pb会报错 jo.put("name", "test"); jo.put("recId", ja); String jsonStr = jo.toJSONString(); System.out.println(jsonStr); //json > pb Builder newBuilder = HelloWordPB.HelloWord.newBuilder(); try { JsonFormat.merge(jsonStr, newBuilder); System.out.println(newBuilder.build().toString()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } //pb > json String printToString = JsonFormat.printToString(newBuilder.build()); System.out.println(printToString); } } 输出: {"name":"test","id":123456,"recId":["1","2"]} id: 123456 name: "test" recId: "1" recId: "2" {"id": 123456,"name": "test","recId": ["1","2"]}
2、pb在构造Builder的时候可以传入一个pb对象:
1)假设我们从redis中读取了一个pb二进制数据,然后反序列化成pb对象:
com.abc.proto.UserRecHistoryPB.UserRecHistory userRecHistory = null; String KEY = MessageFormat.format(CacheConstants.CACHE_KEY_USER_HISTORY_PERF, deviceId); byte[] bs = couchbaseHistoryDao.get(KEY); if (bs != null) { userRecHistory = UserRecHistoryPB.UserRecHistory.parseFrom(bs); }2)接下来对userRecHistory进行修改,修改完毕后需要再保存到redis中: Builder recHistoryBuilder = UserRecHistoryPB.UserRecHistory.newBuilder(userRecHistory); //修改 UserRecHistory build = recHistoryBuilder.build(); String KEY = MessageFormat.format(CacheConstants.CACHE_KEY_USER_HISTORY_PERF, deviceId); int ttl = (int)(System.currentTimeMillis()/1000)+CacheConstants.CACHE_TIME_QUARTER; couchbaseHistoryDao.set(KEY, ttl, build.toByteArray());