如何在YAML文件中为简单的POJO定义映射?

2022-08-31 22:24:20

我正在使用SnakeYAML将某些配置/属性值解析为配置对象(定义如下)。

我的 YAML 文件如下所示:

# Thread
batchLimit: 1000
threadCountLimit: 2

# Some more config
key: value

# Map
keyMapping: <What goes here?>

我的配置类如下所示:

public class Configuration{
  int batchlimit;
  int threadCountLimit;
  ...
  Map<String,String> keyMapping;
}

如何在 YAML 文件中定义 ,以便 SnakeYAML 可以直接解析它?keyMapping


答案 1

以下是它的外观:

#MAP
keyMapping: 
    key1: value1
    key2: value2

通常,YAML 格式具有对键值对的自然支持。看看下面的教程(仅举例来说):https://github.com/Animosity/CraftIRC/wiki/Complete 白痴的介绍到yaml

或者只是谷歌“yaml地图”以获取更多详细信息。


答案 2

Yaml 文件 “AppParams.yml” 与键值对:

someConfig:
    key1: value1
    key2: value2

POJO:

public class ApplicationParameters {
    private Map<String, String> someConfig;

    public ApplicationParameters() {
    }

    public Map<String, String> getSomeConfig() {
        return someConfig;
    }

    public void setSomeConfig(Map<String, String> someConfig) {
        this.someConfig = someConfig;
    }
}

读者:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
File paramFile = new File("AppParams.yml");
ApplicationParameters applicationParameters = mapper.readValue(paramFile, ApplicationParameters.class);

Map<String, String> someConfig = applicationParameters.getSomeConfig();

String key1Value = someConfig.get("key1");    //returns "value1"

上面的示例在 POM.xml中使用了这些依赖项:

 <dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-yaml</artifactId>
        <version>2.9.8</version>
    </dependency>
</dependencies>

推荐