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>

protobuf对象转换成json:

String jsonFormat = JsonFormat.printToString(SomeProto);

json转成protobuf对象:

Message.Builder builder =SomeProto.newBuilder();
String jsonFormat = "json字符串";
JsonFormat.merge(jsonFormat, builder);
原文地址:https://www.cnblogs.com/BensonHe/p/4940270.html