DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Keep Your Application Secrets Secret
  • Exploring Hazelcast With Spring Boot
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Easy Mapping JSON to Java Objects Using Jackson

Trending

  • Key Considerations in Cross-Model Migration
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • Debugging Core Dump Files on Linux - A Detailed Guide
  • Automatic Code Transformation With OpenRewrite
  1. DZone
  2. Coding
  3. Languages
  4. Read YAML in Java with Jackson

Read YAML in Java with Jackson

Jackson is one of the best JSON libraries for Java. Now with the YAML extension of Jackson, we can use Jackson to process YAML in Java.

By 
Manik Magar user avatar
Manik Magar
·
May. 30, 16 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
322.9K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will see how we can use Jackson’s YamlFactory to read YAML files into Java Beans.

What is YAML?

YAML is a human friendly data serialization
standard for all programming languages.

YAML is very handy for writing system configuration files. Yaml.org has a list of libraries that you can use to process YAML files in different languages like PHP, Java, Python, Perl, etc.

Jackson is one of the best JSON libraries for Java. Now with the YAML extension of Jackson, we can use Jackson to process YAML in Java. Under the hood, Jackson’s YAML extension uses the SnakeYAML library to parse YAML.

Maven Project Dependencies

We need Jackason databind and Jackson’s YAML extension. These dependencies should get our demo code working:

<dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-yaml</artifactId>
        <version>2.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.4</version>
    </dependency>
</dependencies>

Reading YAML Files to Java Objects

Let’s consider this sample YAML file for our demo:

# Details of a user
---
name: Test User
age: 30
address:
  line1: My Address Line 1
  line2: Address line 2
  city: Washington D.C.
  zip: 20000
roles: 
  - User
  - Editor

Let’s create a User.java Bean to hold our YAML data:

package com.mms.mja.blog.demo.yaml;

import java.util.Map;

public class User {
    private String name;
    private int age;
    private Map<String, String> address;
    private String[] roles;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Map<String, String> getAddress() {
        return address;
    }
    public void setAddress(Map<String, String> address) {
        this.address = address;
    }
    public String[] getRoles() {
        return roles;
    }
    public void setRoles(String[] roles) {
        this.roles = roles;
    }
}

Jackson at Work

Now, here is our code using Jackson’s YamlFactory to read YAML into User bean:

package com.mms.mja.blog.demo.yaml;

import java.io.File;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

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

public class YamlTesting {

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            User user = mapper.readValue(new File("user.yaml"), User.class);
            System.out.println(ReflectionToStringBuilder.toString(user,ToStringStyle.MULTI_LINE_STYLE));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

ReflectionToStringBuilder is just a util class to print a Java Object to a String. Here is the output of this program:

com.mms.mja.blog.demo.yaml.User@36d4b5c[
  name=Test User
  age=30
  address={line1=My Address Line 1, line2=Address line 2, city=Washington D.C., zip=20000}
  roles={User,Editor}
]

YamlFactory has taken care of mapping address into MAP and roles into a String array. We can also create an Address.java bean class to hold address data and use it instead of MAP in the User bean. YamlFactory will take care of creating the address object and populate it with values from YAML.

YAML Jackson (API) Java (programming language)

Published at DZone with permission of Manik Magar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Keep Your Application Secrets Secret
  • Exploring Hazelcast With Spring Boot
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Easy Mapping JSON to Java Objects Using Jackson

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!