1

我一直在努力设置我的配置以使用 SnakeYAML。我希望我的配置看起来像这样:

connection:
    bind-ip: 0.0.0.0
    plugin-port: 2011
    rtk-port: 2012
    passphrase: abcde12345
updates:
    auto-update: true
    channel: recommended
    build: -1

但结果却是

connection: {bind-ip: 0.0.0.0, connection.passphrase: abcde12345, connection.pluginPort: 2011,
  connection.rtkPort: 2012}
updates: {updates.auto-update: true, updates.channel: Recommended, updates.build: -1}

我有一个 LinkedHashMap ,我可以这样保存:

private LinkedHashMap<String, Map> values;
public void set(String key, Map<String, Object> value) {
        values.put(key, value);
    }

这是我用来填充/加载配置的方法

private void init() {
        Map<String, Object> connection = new LinkedHashMap<String, Object>();

       if (exists("connection.bind-ip"))  {
            bindIp = (String) get("connection.bind-ip");
        }  else {
            connection.put("bind-ip", bindIp);
        }

        if (exists("connection.passphrase"))  {
            passphrase = (String) get("connection.passphrase");
        }  else {
            connection.put("connection.passphrase", passphrase);
        }

        if (exists("connection.pluginPort"))  {
            pluginPort = (Integer) get("connection.rtkPort");
        }  else {
            connection.put("connection.pluginPort", pluginPort);
        }

        if (exists("connection.rtkPort"))  {
            rtkPort = (Integer) get("connection.rtkPort");
        }  else {
            connection.put("connection.rtkPort", rtkPort);
        }

        if (!(connection.isEmpty())) {
            set("connection", connection);
        }

        Map<String, Object> updates = new LinkedHashMap<String, Object>();

        if (exists("updates.auto-update")) {
            autoUpdate = (Boolean) get("updates.auto-update");
        }  else {
            updates.put("updates.auto-update", autoUpdate);
        }

        if (exists("updates.channel")) {
            channel = (String) get("updates.channel");
        }  else {
            updates.put("updates.channel", channel);
        }

        if (exists("updates.build")) {
            build = (Integer) get("updates.build");
        }  else {
            updates.put("updates.build", build);
        }

        if (!(updates.isEmpty())) {
            set("updates", updates);
        }
    }

任何帮助将不胜感激!抱歉有点长

4

2 回答 2

1

简单的回答。创建 YAML 时,请使用DumperOptions和 setDumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK)以及您的 set。不敢相信我错过了:(

于 2013-05-16T02:12:29.820 回答
1

截至org.yaml:snakeyaml:1.17

DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK)
new Yaml(options).dump(data, writer)

只是想知道为什么这不是默认设置。

于 2017-07-05T01:36:52.123 回答