Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Java object instance to YAML using Jackson

I have a 'Example' Pojo class as mentioned below. Can any one tel to save instance of Example class to YAML file using Jackson.

public class Example {

String name;
int value;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getValue() {
    return value;
}

public void setValue(int value) {
    this.value = value;
}

}

like image 357
Ganesh Rao B Avatar asked Sep 27 '17 10:09

Ganesh Rao B


1 Answers

Jackson has a module that supports YAML. Ensure that you add the required dependency to your project, then you can use it as following:

// Create an ObjectMapper mapper for YAML
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

// Write object as YAML file
mapper.writeValue(new File("/path/to/yaml/file"), example);

Alternatively you can write your object as a string:

// Write object as YAML string
String yaml = mapper.writeValueAsString(example);
like image 159
cassiomolin Avatar answered Nov 14 '22 21:11

cassiomolin