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

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;


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);

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

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap