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

如何针对含map类型字段的Avro Schema格式化PubSub JSON消息

GCP PubSub Avro Schema 验证问题解决

问题原因

你的Avro Schema中,attribute字段是一个值类型为联合类型["null", "boolean", "int", "string", "bytes"]的Map。根据Avro的JSON编码规范,当联合类型包含多个非null类型时,非null的取值必须用类型名称作为键的对象包裹,不能直接传入原始值。空Map验证通过是因为它没有键值对,无需检查具体值的类型合规性。

正确的消息格式

要让包含具体值的消息通过验证,需要把每个Map值用对应类型的包装结构包裹,示例如下:

字符串类型值

{
    "attribute": {
        "test": {"string": "hello"}
    }
}

整数类型值

{
    "attribute": {
        "count": {"int": 123}
    }
}

布尔类型值

{
    "attribute": {
        "is_valid": {"boolean": true}
    }
}

Bytes类型值

Bytes类型需要传入Base64编码后的字符串:

{
    "attribute": {
        "data": {"bytes": "aGVsbG8gd29ybGQ="}
    }
}

空值

如果要传null值,直接写null即可:

{
    "attribute": {
        "empty_val": null
    }
}

可选调整方案

如果希望简化部分场景的编码,可以修改Schema,将最常用的类型放在联合类型的首位(Avro会将联合类型的第一个类型视为默认类型,此时该类型的值可以不用包装)。例如把Schema改成:

{
  "type": "record",
  "name": "CloudEvent",
  "fields": [
    {
      "name": "attribute",
      "type": {
        "type": "map",
        "values": ["string", "null", "boolean", "int", "bytes"]
      }
    }
  ]
}

此时字符串类型的值可以直接传入(如"test": "hello"),但其他类型的值仍需要用类型包装结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:17:19