protobuf与json互相转换

protobuf对象不能直接使用jsonlib去转,因为protobuf生成的对象的get方法返回的类型有byte[],而只有String类型可以作为json的key,protobuf提供方法进行转换。

引用maven依赖:

<dependency>
    <groupId>com.googlecode.protobuf-java-format</groupId>
    <artifactId>protobuf-java-format</artifactId>
    <version>1.2</version>
</dependency>

json转成protobuf对象:

//json to protobuf
TestBuilder.Test.Builder builder = TestBuilder.Test.newBuilder();
String jsonFormat = "{\"name\":\"张三\"}";
try {
  JsonFormat.merge(jsonFormat,builder);
 } catch (JsonFormat.ParseException e) {
   e.printStackTrace();
}

protobuf对象转换成json:

//protobuf to json
TestBuilder.Test test = builder.build();
String s = JsonFormat.printToString(test);
System.out.println(s);

posted on 2018-07-10 16:40  腾飞的鹰  阅读(5052)  评论(0)    收藏  举报

导航