将 json 解组到具有 oneof 类型的 protobuf 中

问题描述 投票:0回答:1

我正在开发符合 openapi 3.0.0 的 api 定义的东西 根据 openapi 3.0.0,oneOf 类型字段可以采用上述任何一种类型的值。

pet:
  oneOf:
    - $ref: '#/components/schemas/Cat'
    - $ref: '#/components/schemas/Dog'
components:
  schemas:
    Dog:
      type: object
      properties:
        bark:
          type: boolean
        breed:
          type: string
          enum: [Dingo, Husky, Retriever, Shepherd]
    Cat:
      type: object
      properties:
        hunts:
          type: boolean
        age:
          type: integer

根据 swagger,如果宠物类型是猫,则正确的 json 模式可以是 {"pet":{"hunts":false,"age":3}} ,如果是狗,则为 {" pet":{"bark":true,"breed":"哈士奇"}}

它没有明确指定类型,并假设服务器可以根据存在的字段对其进行解码。

我使用 protobuf 来管理数据类型,因为我还需要使用 grpc 将其发送到不同的微服务,对于这种示例,我想到使用 proto 中的 oneOf 。

原型的定义是

message pet{
oneof pet{
Cat cat = 1;
Dog dog = 2;
}
}
message Cat {
boolean hunts = 1;
int age = 2;
}
message Dog {
boolean bark = 1;
string breed =2;
}

但是将 json 解组为 pet 类型会失败,因为它期望 json 消息必须有一个字段 pet,然后是狗或猫,我猜。

从 openapi 规范到 golang 的 oneof 类型是否遵循任何其他约定?

从 openapi 规范到 golang 的 oneof 类型是否遵循任何其他约定?

go protocol-buffers openapi
1个回答
0
投票

您是正确的,您提供的 Protobuf 示例的 JSON 等效项与 OpenAPI 不匹配:

[
  {
    "dog":{
      "bark":true,
      "breed":"Border Collie"
    }
  },
  {
    "cat":{
      "hunts":true,
      "age":4
    }
  }
]

您可以考虑使用 Google 的知名类型,特别是

Value

message M {
    google.protobuf.Value pet = 1;
}

不幸的是,你失去了 Protobuf 想要使用

oneof
强制执行的类型安全性,但是,你得到了你想要的(无类型)JSON:

[
  {
    "pet":{
      "bark":true,
      "breed":"Border Collie"
    }
  },
  {
    "pet":{
      "hunts":true,
      "age":4
    }
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.