简体   繁体   中英

Java - Parse Yaml to Json

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM