You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何将Protobuf消息转换为JSON?

在Kotlin中转换Protobuf消息为JSON的简便方法

方法一:直接使用官方JsonFormat(兼容Kotlin)

你觉得JsonFormat在Kotlin里无法使用,大概率是依赖引入不全或者用法没调整到位——它其实完全可以在Kotlin环境正常工作:

  1. 先确保引入Protobuf的JSON工具依赖(以Gradle为例):
implementation("com.google.protobuf:protobuf-java-util:3.25.3")
  1. 直接调用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工具类,用法更直观:

  1. 确保依赖版本不低于3.20.0:
implementation("com.google.protobuf:protobuf-java-util:3.25.3")
  1. 转换代码示例:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 15:02:33