Schütze Schütze - 1 month ago 7
YAML Question

Java: Load data into variables from a .yaml file

I've a Java program that should connect to two other machines (IP addresses and ports are known) and do a data comparison task.

Instead of hardcoding the IP and port in the Java source file, I created a

config.yaml
file and stored these there as follows, let's say this is the context of that file:

config.yaml:

other machines:
-"firstMachineAddress:162.242.195.82"
-"secondMachineAddress:50.31.209.229"
-"firstTargetPort:4041"
-"secondTargetPort:4042"


Now I want to load these values in my Java source file and assign them to the variables I created already, such as:

sampleClass.java:

// addresses of the machines which we will connect
public final InetAddress firstMachineAddress = "";
public final InetAddress secondMachineAddress = "";
private final int firstTargetPort = "";
private final int secondTargetPort = "";


I was wondering if Java provides a convenient way to achieve this?

Answer

https://github.com/FasterXML/jackson-dataformat-yaml

Copy paste below

Maven dependency

To use this extension on Maven-based projects, use following dependency:

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
  <version>2.8.3</version>
</dependency>

Usage

Usage is as with basic JsonFactory; most commonly you will just construct a standard ObjectMapper with com.fasterxml.jackson.dataformat.yaml.YAMLFactory, like so:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
User user = mapper.readValue(yamlSource, User.class);

but you can also just use underlying YAMLFactory and parser it produces, for event-based processing:

YAMLFactory factory = new YAMLFactory();
JsonParser parser = factory.createJsonParser(yamlString); // don't be fooled by method name...
while (parser.nextToken() != null) {
  // do something!
}