用Java(Cucumber 7.6.0/Gherkin-Java 24.0.0)解析Gherkin Feature为JSON
Java解析Gherkin Feature文件为JSON(基于Cucumber 7.6.0/Gherkin-Java 24.0.0)
1. 添加依赖
先在项目中引入Gherkin解析库和JSON序列化库(以Maven为例):
<dependencies> <!-- Gherkin核心解析库 --> <dependency> <groupId>io.cucumber</groupId> <artifactId>gherkin</artifactId> <version>24.0.0</version> </dependency> <!-- Jackson用于对象转JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency> </dependencies>
2. 核心解析代码
以下代码实现从本地Feature文件读取内容、解析为Gherkin AST对象,最终序列化为JSON字符串:
import io.cucumber.gherkin.GherkinParser; import io.cucumber.gherkin.Feature; import io.cucumber.messages.types.Location; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.nio.file.Files; public class GherkinToJsonConverter { public static void main(String[] args) throws Exception { // 读取目标Feature文件 File featureFile = new File("path/to/your/feature/file.feature"); String featureContent = Files.readString(featureFile.toPath()); // 解析为Gherkin Feature AST对象 Feature feature = GherkinParser.parse(featureContent, new Location(1, 1)); // 序列化为格式化的JSON字符串 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writerWithDefaultPrettyPrinter(); String jsonOutput = objectMapper.writeValueAsString(feature); // 输出或保存JSON System.out.println(jsonOutput); // 保存到文件:Files.writeString(new File("output.feature.json").toPath(), jsonOutput); } }
3. 自定义JSON结构(可选)
如果原生AST的JSON结构不符合前端业务需求,可以自定义DTO类,映射Feature对象的关键字段后再序列化:
import java.util.List; // 自定义Feature数据传输类 public class FeatureDto { private String name; private String description; private List<String> tags; private List<ScenarioDto> scenarios; // 构造器、getter/setter省略 // 从Gherkin Feature对象转换为自定义DTO public static FeatureDto fromFeature(Feature feature) { FeatureDto dto = new FeatureDto(); dto.setName(feature.getName()); dto.setDescription(feature.getDescription()); dto.setTags(feature.getTags().stream().map(tag -> tag.getName()).toList()); dto.setScenarios(feature.getChildren().stream() .filter(child -> child instanceof io.cucumber.gherkin.Scenario) .map(child -> (io.cucumber.gherkin.Scenario) child) .map(scenario -> { ScenarioDto scenarioDto = new ScenarioDto(); scenarioDto.setName(scenario.getName()); scenarioDto.setTags(scenario.getTags().stream().map(tag -> tag.getName()).toList()); scenarioDto.setSteps(scenario.getSteps().stream().map(step -> step.getText()).toList()); return scenarioDto; }) .toList()); return dto; } } // 自定义Scenario数据传输类 class ScenarioDto { private String name; private List<String> tags; private List<String> steps; // 构造器、getter/setter省略 }
使用自定义DTO时,只需替换序列化逻辑:
FeatureDto featureDto = FeatureDto.fromFeature(feature); String customJson = objectMapper.writeValueAsString(featureDto);
4. 过滤逻辑提示
解析后的JSON(或DTO对象)可直接实现以下过滤需求:
- 按标签过滤:匹配Feature或Scenario的
tags字段 - 按场景过滤:匹配Scenario的
name或steps字段 - 按功能文本过滤:匹配Feature的
name或description字段
内容的提问来源于stack exchange,提问作者Siddharth Mishra
相关产品推荐
相关产品推荐

