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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Join us today at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  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.

Manik Magar user avatar by
Manik Magar
·
May. 30, 16 · Tutorial
Like (11)
Save
Tweet
Share
315.35K 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.

Popular on DZone

  • Exploring the Benefits of Cloud Computing: From IaaS, PaaS, SaaS to Google Cloud, AWS, and Microsoft
  • The Enterprise, the Database, the Problem, and the Solution
  • Data Mesh vs. Data Fabric: A Tale of Two New Data Paradigms
  • Type Variance in Java and Kotlin

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: