OpenAPI Generator生成代码出现com.google.gson导入错误求助
解决OpenAPI Generator生成代码的Gson依赖错误及Schema匹配问题
一、解决"java: package com.google.gson does not exist"错误
OpenAPI Generator生成Java代码时,默认依赖Gson做JSON序列化/反序列化,但部分场景下依赖不会自动写入构建文件,手动补充即可:
1. Maven项目
在pom.xml的<dependencies>块中添加:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- 可替换为最新稳定版 --> </dependency>
执行mvn clean install刷新依赖。
2. Gradle项目
在build.gradle的dependencies块中添加:
implementation 'com.google.code.gson:gson:2.10.1'
执行gradle build下载并引入依赖。
二、修正OpenAPI Schema以匹配Elasticsearch返回结果
你当前的api.yml中Result schema和Elasticsearch实际返回的JSON结构完全不匹配,后续必然会出现反序列化失败问题,必须修正:
修正后的components/schemas代码:
components: schemas: Result: type: object properties: took: type: integer timed_out: type: boolean _shards: type: object properties: total: type: integer successful: type: integer skipped: type: integer failed: type: integer hits: type: object properties: total: type: object properties: value: type: integer relation: type: string max_score: type: number hits: type: array items: type: object properties: _index: type: string _id: type: string _score: type: number _source: type: object properties: title: type: string url: type: string content: type: string dt_creation: type: string reading_time: type: integer suggest: type: object properties: my-suggestion: type: array items: type: object properties: text: type: string offset: type: integer length: type: integer options: type: array items: type: object properties: text: type: string score: type: number freq: type: integer Error: type: object required: - message properties: message: description: 人类可读的错误信息 type: string
关键修正点:
- 完全对齐Elasticsearch返回的JSON层级,包括
_shards、嵌套的hits数组、suggest下的数组结构 - 修正了字段名(比如原Schema的
Hits应为小写hits,abs实际对应返回的content) - 补充了所有字段的类型定义,确保序列化/反序列化正常工作
修正Schema后,重新用OpenAPI Generator生成代码,就能正确处理Elasticsearch的查询结果了。
内容的提问来源于stack exchange,提问作者user25397086
相关产品推荐
相关产品推荐

