Open In App

YAML to List of Objects in Spring Boot

In this article, let us dive into Converting YAML files to a List of Objects in Spring boot. To understand this we need to have some knowledge of the following pre-requisites.

This conversion will help us to inject the YAML data into other classes in the same way as we do for other Spring beans.



Converting YAML Files to List of Objects in Spring Boot

Step 1: Create your spring boot project

Note: For this Project, I am using Eclipse IDE for Java and Web Development 2023-06



Note: Here, I am using Maven build management tool and Java version 8 (make sure, you are using atleast Java 8)

Step 2: Configure the pom.xml

Once your project is created by configuring default options, You need to configure your Project Object Model i.e. pom.xml file ( this will be available only if you are using Maven).

In the pom.xml file, you need to add the dependencies to handle

By default, pom.xml is the last file you can find in your project structure. Copy and paste the below dependencies enclosing the <dependencies> tag in the pom.xml

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Step 3: Creating the YAML file

For this step, we first need to create and configure the resources that are required for this project. In a YAML formatted file.

Create a file with a .yml extension in the src/main/resources folder in your project structure. For instance, I have named the file as data.yml. After creating this file, the project structure will look like the following.

Project Structure:

Add some sample data in the data.yml file in a key-value pair. I have added the person’s details along with their name and age.

//data.yml
persons:
- name: poojitha
age: 20
- name: Ravi
age: 30
- name: Rahul
age: 35

Step 4: Creation of Java class

Now in this, we will see how to parse the data.yml file content into data members or variables in the context of Object-oriented programming in Java, to do so following the mentioned step.

Project structure:




/* Persons.Java: This class represents the data in the data.yml file 
in terms of attributes according to Java programming language. */
  
package com.example.demo.model;
  
public class Persons {
    private String name;
    private int age;
    
// respective getters and setters to access the private variables
    
    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;
    }
}

Explanation:

Note: Developers can use Lombok library to generate getter, setters, etc. To reduce the boiler plate code.

Step 5: Creating the Structure of YAML

We have already created a class that represents the individual attributes of our data.yml file. Let us create a class that represents the entire structure of our YAML. To do this, we need to create another class in the model sub-package that we created earlier.

Project structure:




package com.example.demo.model;
  
import java.util.List;
  
public class PersonsList {
      /*  This represents the entire structure of data.yml file 
    in the form of List datastructure */
    private List<Persons> persons;
      
      //respective getter and setter methods
    public List<Persons> getPersons() {
        return persons;
    }
  
    public void setPersons(List<Persons> persons) {
        this.persons = persons;
    }
}

Explanation:

Step 6: Creating a service class

Let us create a service class, Spring’s component scanning will automatically scan that. To achieve this, we need to create a sub-package named service inside our default package i.e. src/main/java.

Project Structure:




// PersonsService to handle the 
// conversion logic
  
package com.example.demo.service;
  
import com.example.demo.model.Persons;
import com.example.demo.model.PersonsList;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.IOException;
import java.util.List;
import org.springframework.stereotype.Service;
  
/* This class is annotated with @Service in order to
     automatically scanned by Spring boot*/
@Service
public class PersonsService {
  
    /* This method is used to read and parse the YAML file*/
    public List<Persons> readMyObjects() throws IOException{
        
        /* The ObjectMapper object is created and configured
        to use YAML file and the YAMLFACTORY is to configure
        the objectMapper in order to parse the YAML file */
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        
        /* The following code helps to read the data.yml file 
        with the help of above created objectMapper and store
        it in the personsList object. */
        PersonsList personsList = objectMapper
          .readValue(getClass().getResourceAsStream("/data.yml"),
            PersonsList.class);
        
        
          //invokes the getter to get the list of persons
        return personsList.getPersons(); 
    }
}

Explanation:

This ObjectMapper creates a new object with YAMLFactory as a parameter and this object is used to read the data in the data.yml later the result is returned which is the personsList object as a list of persons by using the getter method

Step 7: Creating the Controller class:

Let us create the Controller class for our project.

Project Structure:




//PersonsController.java
  
package com.example.demo.controller;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
  
import com.example.demo.model.Persons;
import com.example.demo.service.PersonsService;
  
import java.io.IOException;
import java.util.List;
  
//This Class annotated with @RestController to handle the HTTP requests and responses
@RestController
public class PersonsController {
    @Autowired
    private PersonsService personsService;
      
      /* The @GetMapping method is used to store the result of the below method in the 
      mentioned endpoint i.e. "/persons" */
    @GetMapping("/persons")
    public List<Persons> getPersons() throws IOException {
        return personsService.readPersons(); 
    }
}

Explanation:

Steps to run the application:

To run the application, right-click on the project in the project explorer, and click Run as > Spring Boot App.

Console View:

Console output tells the successful compilation and running of our spring boot project.

Output:

Web view of the converted data of .yml to java objects is displayed in the form of JSON.


Article Tags :