Schütze Schütze - 6 months ago 52
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

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


other machines:

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

// 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?


Copy paste below

Maven dependency

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



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!