Skip to content
Advertisement

How do I convert from YAML to JSON in Java?

I just want to convert a string that contains a yaml into another string that contains the corrseponding converted json using Java.

For example supose that I have the content of this yaml

JavaScript

in a String called yamlDoc:

JavaScript

I want some method that can convert the yaml String into another String with the corresponding json, i.e. the following code

JavaScript

should print:

JavaScript

I want to know if exists something similar to the convertToJson() method in this example.

I tried to achieve this using SnakeYAML, so this code

JavaScript

constructs a map that contain the parsed YAML structure (using nested Maps). Then if there is a parser that can convert a map into a json String it will solve my problem, but I didn’t find something like that neither.

Any response will be greatly appreciated.

Advertisement

Answer

Here is an implementation that uses Jackson:

JavaScript

Requires:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement