Syed
Syed

Reputation: 2607

Convert Yaml properties object to Java object

Here is my Yaml properties file

bb:
  employees:
   -
    employee1:
      name: Syed
      locations:
        - HYD
        - MAA
   -
    employee2:
      name: Adhil
      locations:
        - BOM
        - DEL

I want to convert the object into my POJO in my applicaiton. However I'm not able to do it, it always returns null.

Is there anything which I'm missing?

@Data

@Builder
 @AllArgsConstructor
@NoArgsConstructor
@Configuration
@ConfigurationProperties(prefix = "bb")
public class EmpConfig {

    EmployeeDetails employees;
}

EmployeeDetails Class

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Configuration

public class EmployeeDetails {

    List<Map<String, List<String>>> details;
}

Upvotes: 2

Views: 820

Answers (2)

Suraj Gautam
Suraj Gautam

Reputation: 1590

This worked for me without modifying your structure.

YAML looks like:

bb:
  employees:
      employee:
        - name: Syed
          locations:
            - HYD
            - MAA

        - name: Adhil
          locations:
            - BOM
            - DEL

The output is

enter image description here

Hope it helps!

Upvotes: 1

Saphyra
Saphyra

Reputation: 460

It worked me this way:

The YAML (called application.yaml) (dashes removed before the employeeIds (employee1, employee2))

bb:
  employees:
    employee1:
      name: Syed
      locations:
        - HYD
        - MAA
    employee2:
      name: Adhil
      locations:
        - BOM
        - DEL

Config class:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Configuration
@ConfigurationProperties(prefix = "bb")
public class EmpConfig {
    private Map<String, EmployeeDetails> employees;
}

EmployeeDetails:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeDetails {
    private String name;
    private List<String> locations;
}

So basically you have problems with the syntax, and the data types, so Spring cannot parse the configuration file.

Upvotes: 1

Related Questions