使用Modelina生成Kotlin数据类:必填字段非空及类型问题求助
问题排查与解决
针对你遇到的必填字段生成可空类型、int64类型被转为String? 这两个问题,按以下步骤排查修复:
1. 校验AsyncAPI 3.0规范的必填字段定义
Modelina识别必填字段的前提是:required数组必须直接定义在目标Schema的根层级,而非嵌套在properties的子字段中。请确保你的规范结构类似:
components: schemas: TestMessage: type: object properties: id: type: string version: type: integer format: int64 name: type: string # 关键:required数组必须在Schema根层级 required: - id - version - name
如果required位置错误,Modelina会默认所有字段为非必填,生成可空类型。
2. 修正int64到Kotlin类型的映射
Modelina默认将int64映射为String(避免数值溢出场景),但你可以通过配置强制映射为Kotlin的Long:
- 创建
modelina-config.json配置文件:
{ "kotlin": { "typeMapping": { "integer": { "int64": "Long" } } } }
- 修改生成命令,引入配置文件:
asyncapi generate models kotlin -o=generated --packageName=com.test.demo --config=modelina-config.json ./asyncapi.yaml
3. 升级Modelina到最新版本
旧版本的Modelina对AsyncAPI 3.0的支持存在兼容性bug,先执行升级:
npm install -g @asyncapi/modelina
4. 检查Schema引用是否正确
确保消息的payload是直接引用TestMessage Schema,而非重新定义了一份缺失required的Schema。例如:
channels: testChannel: publish: message: payload: $ref: '#/components/schemas/TestMessage'
如果直接在payload内重复定义Schema,需同步补全required数组。
内容的提问来源于stack exchange,提问作者Markward Schubert
相关产品推荐
相关产品推荐

