Saturday, May 16, 2015

How to convert a YAML file to a Java object using SnakeYAML

To convert a YAML file to a Java object using SnakeYAML,

if you have `src/main/resources/scenario/test_http.yaml` as follows:

name: test_http
testTarget: HTTP_SERVER
testCases:
  - id: 1
    timeoutInMillis: 100
    initialWorkerCount: 10
    rampUpStep: 1
    durationInSeconds: 300
  - id: 2
    timeoutInMillis: 100
    initialWorkerCount: 10
    rampUpStep: 10
    durationInSeconds: 300

you can convert the file to a Java object as follows:

  @Test
  public void test() throws FileNotFoundException {
    File file = ResourceUtils.getFile("classpath:scenario/test_http.yml");
    Yaml yaml = new Yaml(new Constructor(PerformanceTestScenario.class));
    PerformanceTestScenario testScenario
        = (PerformanceTestScenario) yaml.load(new FileReader(file));
    System.out.println(testScenario);
  }

Reference:
https://code.google.com/p/snakeyaml/wiki/Documentation

No comments:

Post a Comment