YAML
suggest changeYAML (YAML Ain't Markup Language) is a human-readable data serialization format extensively used across the Java ecosystem for configuration files (such as Spring Boot's application.yml), Kubernetes manifests, and build pipelines.
In Java, two primary libraries are used to parse and generate YAML:
- SnakeYAML: A dedicated, lightweight YAML parser and emitter compliant with YAML 1.1.
- Jackson YAML (
jackson-dataformat-yaml): An extension to the Jackson JSON library that leverages the sameObjectMapperannotations and data binding infrastructure.
1. Using Jackson Dataformat YAML
If your project already uses Jackson for JSON, using Jackson's YAML dataformat provides a unified, annotation-driven programming model.
Dependency
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.22.3</version>
</dependency>
Parsing YAML into a Java Record or POJO
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.File;
import java.util.List;
public class JacksonYamlExample {
public record ServerConfig(
@JsonProperty("host") String host,
@JsonProperty("port") int port,
@JsonProperty("endpoints") List<String> endpoints,
@JsonProperty("tls-enabled") boolean tlsEnabled
) {}
public static void main(String[] args) throws Exception {
String yamlContent = """
host: "api.example.com"
port: 8443
tls-enabled: true
endpoints:
- "/health"
- "/v1/users"
- "/v1/orders"
""";
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
ServerConfig config = mapper.readValue(yamlContent, ServerConfig.class);
System.out.printf("Host: %s, Port: %d, TLS: %b%n",
config.host(), config.port(), config.tlsEnabled());
System.out.println("Endpoints: " + config.endpoints());
}
}
Serializing Java Objects to YAML
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import java.util.List;
public class YamlExportExample {
public static void main(String[] args) throws Exception {
YAMLFactory factory = new YAMLFactory()
.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER); // Omits the leading "---"
ObjectMapper mapper = new ObjectMapper(factory);
var config = new JacksonYamlExample.ServerConfig(
"localhost", 8080, List.of("/metrics"), false
);
String yamlOutput = mapper.writeValueAsString(config);
System.out.println(yamlOutput);
}
}
2. Using SnakeYAML
SnakeYAML is directly embedded in many frameworks (including Spring Boot).
Dependency
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.7</version>
</dependency>
Safe Parsing to Maps and Primitives
By default, SnakeYAML v2.0+ enforces safe loading to protect against remote code execution via arbitrary class instantiation:
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.LoaderOptions;
import java.io.InputStream;
import java.util.Map;
public class SnakeYamlExample {
public static void main(String[] args) {
String yamlInput = """
database:
host: "10.0.0.12"
port: 5432
pool-size: 20
""";
LoaderOptions options = new LoaderOptions();
Yaml yaml = new Yaml(options);
Map<String, Object> data = yaml.load(yamlInput);
@SuppressWarnings("unchecked")
Map<String, Object> db = (Map<String, Object>) data.get("database");
System.out.println("DB Host: " + db.get("host"));
System.out.println("DB Port: " + db.get("port"));
}
}
Type-Safe POJO Loading with Tag Inspectors (SnakeYAML 2+)
When deserializing directly into a custom class, specify allowed classes using a TagInspector:
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.inspector.TagInspector;
import org.yaml.snakeyaml.nodes.Tag;
public class SafePojoLoading {
public static class AppSettings {
public String appName;
public int timeoutSeconds;
// SnakeYAML requires a no-arg constructor
public AppSettings() {}
}
public static void main(String[] args) {
String yaml = """
appName: PaymentProcessor
timeoutSeconds: 30
""";
LoaderOptions loaderOptions = new LoaderOptions();
// Explicitly allow AppSettings to be instantiated
loaderOptions.setTagInspector(new TagInspector() {
@Override
public boolean isGlobalTagAllowed(Tag tag) {
return tag.getClassName().equals(AppSettings.class.getName());
}
});
Constructor constructor = new Constructor(AppSettings.class, loaderOptions);
Yaml yamlParser = new Yaml(constructor);
AppSettings settings = yamlParser.load(yaml);
System.out.println("Loaded: " + settings.appName + " (timeout: " + settings.timeoutSeconds + "s)");
}
}
3. Parsing Multi-Document YAML Files
A single YAML file can contain multiple documents separated by ---. SnakeYAML's loadAll handles this seamlessly:
import org.yaml.snakeyaml.Yaml;
public class MultiDocExample {
public static void main(String[] args) {
String multiDoc = """
---
kind: Service
name: web-svc
---
kind: Deployment
name: web-deploy
""";
Yaml yaml = new Yaml();
for (Object doc : yaml.loadAll(multiDoc)) {
System.out.println("Document: " + doc);
}
}
}
4. Security Considerations
- Never use untrusted YAML with default polymorphic typing: Older versions of SnakeYAML allowed instantiating arbitrary classes via tags like
!!com.sun.rowset.JdbcRowSetImpl, leading to severe deserialization vulnerabilities (RCE). - Use
SafeConstructor: In SnakeYAML, always usenew Yaml(new SafeConstructor(new LoaderOptions()))when parsing untrusted input. - In Jackson: Avoid
enableDefaultTyping()onObjectMapperwithout a strictPolymorphicTypeValidator.