Generate POJO from .yaml

11,083

Solution 1

The problem is that YAML describes objects, not classes. In general, you cannot automatically derive a POJO structure from a given YAML file. Take, for example, this YAML:

one: foo
two: bar

In YAML, this is a mapping with scalar keys and values. However, there are multiple possibilities to map it to Java. Here are two:

HashMap<String, String>
class Root {
    String one;
    String bar;
}

To know which one is the right mapping, you would need a schema definition like those for XML. Sadly, YAML currently does not provide a standard way of defining a schema. Therefore, you define the schema by writing the class hierarchy your YAML should be deserialised into.

So, in contrary to what you may think, writing the POJOs is not a superfluous action that could be automated, but instead is a vital step for including YAML in your application.

Note: In the case that you actually want to use YAML to define some data layout and then generate Java source code from it, that is of course possible. However, you'd need to be much more precise in your description to get help on that.

Solution 2

As pointed out in the comments by Jack Flamp, you can use an online tool (jsonschema2pojo) to convert a sample yaml file to its equivalent POJO classes. This tool can convert json or yaml data to corresponding POJO classes and I have used it successfully in the past.

That being said, the tool is forced to make certain "assumptions" when you are using a yaml file(instead of yaml schema). So, it would be a good idea to look at the generated classes carefully before you start using them.

You can find more information about how to use this online tool from its wiki page.

The Accepted Answer is incomplete.

Solution 3

You can try to use https://editor.swagger.io/ After importing yaml file You can generate Java REST Client project through menu with correspondent POJO classes.

Share:
11,083
Mabi
Author by

Mabi

Updated on July 17, 2022

Comments

  • Mabi
    Mabi almost 2 years

    I'm looking for a solution which automatically generates POJO classfiles from a given .yaml-Files but have not found anything like this yet. I can not imagine that it should be the only way to write these classes yourself.