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

Java中如何自定义Protobuf ApiUUID的JSON转换为UUID字符串

如何将Protobuf的ApiUUID序列化为JSON时输出标准UUID字符串(Java实现)

要实现把ApiUUID转换成标准UUID字符串输出,你可以利用Protobuf的JsonFormat扩展机制,自定义类型适配器(TypeAdapter)覆盖默认序列化逻辑,具体步骤如下:

1. 实现自定义TypeAdapter

编写JsonFormat.TypeAdapter<ApiUUID>,将ApiUUID的most和least字段转换为Java的UUID对象,再输出为标准字符串格式:

import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.UUID;

public class ApiUuidTypeAdapter implements JsonFormat.TypeAdapter<ApiUUID> {
    @Override
    public void write(JsonFormat.Writer writer, ApiUUID value) throws IOException {
        // 转换为UUID对象
        UUID uuid = new UUID(value.getMost(), value.getLeast());
        // 写入标准UUID字符串
        writer.writeString(uuid.toString());
    }

    @Override
    public ApiUUID read(JsonFormat.Parser parser) throws IOException {
        // 若需反序列化JSON到ApiUUID,补充此逻辑
        String uuidStr = parser.readString();
        UUID uuid = UUID.fromString(uuidStr);
        return ApiUUID.newBuilder()
                .setMost(uuid.getMostSignificantBits())
                .setLeast(uuid.getLeastSignificantBits())
                .build();
    }
}

2. 注册TypeAdapter到TypeRegistry

创建TypeRegistry并注册自定义适配器,让JsonFormat识别ApiUUID的处理规则:

import com.google.protobuf.util.JsonFormat;

// 构建并注册类型适配器
JsonFormat.TypeRegistry typeRegistry = JsonFormat.TypeRegistry.newBuilder()
        .add(ApiUUID.getDescriptor())
        .addTypeAdapter(ApiUUID.class, new ApiUuidTypeAdapter())
        .build();

3. 使用自定义配置的Printer生成JSON

创建带有TypeRegistry的Printer,替代默认Printer完成序列化:

// 初始化自定义Printer
JsonFormat.Printer printer = JsonFormat.printer()
        .omittingInsignificantWhitespace()
        .usingTypeRegistry(typeRegistry);

// 序列化Data对象为JSON
String json = printer.print(planningData);

效果验证

处理后,JSON中的id字段会输出为标准UUID字符串格式:

{"id":"5f8a1d2b-3c4e-5678-90ab-cdef12345678","name":"example"}

补充说明

  • 若不需要反序列化,可仅实现write方法,read方法抛出UnsupportedOperationException即可
  • 该方案完全保留Protobuf二进制序列化的性能优势,仅修改JSON序列化逻辑

内容的提问来源于stack exchange,提问作者Mavo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:28