Reputation: 3956
Python and Ruby have very nice libraries for parsing a Yaml file into a JSON object.
The parser needs to support Yaml Anchor and References.
Input
info: &info
legs: 4 legs
type: pet
dog: *info
cat: *info
Desired output:
{
"info": {
"legs": "4 legs",
"type": "pet"
},
"dog": {
"legs": "4 legs",
"type": "pet"
},
"cat": {
"legs": "4 legs",
"type": "pet"
}
}
I first tried the Jackson YAMLFactory. That library did not generically support anchors and references.
What is a good solution in Java for parsing Yaml into a JSON object?
Upvotes: 2
Views: 6165
Reputation: 3956
The following solution seemed to work.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.yaml.snakeyaml.Yaml;
public class YamlParser {
public static void main(String[] argv) {
File f = new File("my.yml");
final Yaml yaml = new Yaml();
try {
final Object loadedYaml = yaml.load(new FileReader(f));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(loadedYaml,LinkedHashMap.class);
System.out.println(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
With the following maven dependencies.
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.21</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Upvotes: 5