Kotlin中如何将Protobuf消息转换为JSON?
在Kotlin中转换Protobuf消息为JSON的简便方法
方法一:直接使用官方JsonFormat(兼容Kotlin)
你觉得JsonFormat在Kotlin里无法使用,大概率是依赖引入不全或者用法没调整到位——它其实完全可以在Kotlin环境正常工作:
- 先确保引入Protobuf的JSON工具依赖(以Gradle为例):
implementation("com.google.protobuf:protobuf-java-util:3.25.3")
- 直接调用
JsonFormat.printer()完成转换:
import com.google.protobuf.util.JsonFormat val myProto = MyProto.newBuilder().setId("id").build() val json: String = JsonFormat.printer().print(myProto)
如果需要自定义输出格式,比如忽略冗余空格、包含默认值字段,可以给printer添加配置:
val json = JsonFormat.printer() .omittingInsignificantWhitespace() // 生成紧凑格式的JSON .includingDefaultValueFields() // 输出包含默认值的字段 .print(myProto)
方法二:用Kotlin扩展函数简化调用
为了贴合Kotlin的语法风格,可以自定义一个扩展函数,后续调用更简洁:
import com.google.protobuf.Message import com.google.protobuf.util.JsonFormat fun Message.toJson( omitWhitespace: Boolean = true, includeDefaults: Boolean = false ): String { val printer = JsonFormat.printer() .run { if (omitWhitespace) omittingInsignificantWhitespace() else this } .run { if (includeDefaults) includingDefaultValueFields() else this } return printer.print(this) }
之后直接在Protobuf实例上调用即可:
val myProto = MyProto.newBuilder().setId("id").build() val json: String = myProto.toJson() // 按需传参:myProto.toJson(includeDefaults = true)
方法三:使用新版Protobuf的Json类(推荐)
从Protobuf 3.20.0版本开始,官方推出了更简洁的Json工具类,用法更直观:
- 确保依赖版本不低于3.20.0:
implementation("com.google.protobuf:protobuf-java-util:3.25.3")
- 转换代码示例:
import com.google.protobuf.Json val myProto = MyProto.newBuilder().setId("id").build() val json: String = Json.toJson(myProto)
同样支持自定义输出选项:
import com.google.protobuf.Json import com.google.protobuf.JsonWriterOptions val options = JsonWriterOptions.newBuilder() .setOmitInsignificantWhitespace(true) .setIncludeDefaultValueFields(false) .build() val json = Json.toJson(myProto, options)
内容的提问来源于stack exchange,提问作者Smajl
相关产品推荐
相关产品推荐

