Java实现yaml转map
时间: 2023-07-11 17:49:59 浏览: 183
java 一键读取yaml、propertites配置文件内容,转换为一级map
要实现yaml转map,可以使用Jackson库和SnakeYAML库。
首先,需要在项目中引入以下两个依赖:
```xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.28</version>
</dependency>
```
然后,可以编写以下代码:
```java
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.yaml.snakeyaml.Yaml;
public class YamlToMap {
public static void main(String[] args) throws IOException {
String yamlString = "key1: value1\nkey2: value2\nkey3:\n key4: value4\n";
Yaml yaml = new Yaml();
Map<String, Object> yamlMap = yaml.load(yamlString);
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(yamlMap);
Map<String, Object> jsonMap = objectMapper.readValue(jsonString, Map.class);
System.out.println(jsonMap);
}
}
```
上述代码将yaml字符串转换为Map对象,并将Map对象转换为JSON字符串,最终输出Map对象。其中,使用SnakeYAML库将yaml字符串转换为Map对象,使用Jackson库将Map对象转换为JSON字符串和Map对象。
阅读全文