Convert Java Object to YAML using Jackson Library


Post Banner

In this tutorial, we will see how to convert a Java Object into a YAML String/File using Jackson Library,

Step 1: Add Jackson YAML Dependency

Maven:
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.13.4</version>
</dependency>
Gradle:
implementation group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: '2.13.4'

Step 2: Java Object to YAML

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.IOException;

public class JavaObjectToYaml {

    public static void main(String[] args) throws IOException {

       String[] subjects = {"Java","PHP","Python","C#"};
       Student student = new Student("Andrew",24,"Computers", subjects);
       ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
       String yamlString = objectMapper.writeValueAsString(student);
       System.out.println(yamlString);
    }
}
Output:

name: "Andrew"
age: 24
course: "Computers"
subjects:
- "Java"
- "PHP"
- "Python"
- "C#"



Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.