0

I'm using jackson in my java project

        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>2.10.3</version>
        </dependency>

I want to map this yaml to java classes

  Settings:
    - Setting: number1
      Environments:
        - Name: name
          Value: 3

What I can think of now is this

public class MyYaml {
    private Set<Setting> settings;

    @JsonProperty("Settings")
    public String getSettings() {
        return settings;
    }

    public class Setting {
        private String name;
        private Environments environments;

        @JsonProperty("??????????????????????")
        public String getName() {
            return name;
        }


Now my question is how to map that attribute name for Setting class so that it returns name as the value

TrongBang
  • 923
  • 1
  • 12
  • 23

1 Answers1

0

The field name.

A full example

@Getter @Setter @ToString // lombok for simplicity, can be written at hand
static class MyYaml {
    private Set<Setting> settings;
}

@Getter @Setter @ToString
static class Setting {
    @JsonProperty("setting") // << REQUIRED
    private String name;
    private Set<Environment> environments;
}

@Getter @Setter @ToString
static class Environment {
    private String name;
    private int value;
}

usage example

System.out.println(new ObjectMapper(new YAMLFactory()).readValue("settings:\n" +
        "  - setting: setting1\n" +
        "    environments:\n" +
        "      - name: env1\n" +
        "        value: 31\n" +
        "      - name: env2\n" +
        "        value: 12\n" +
        "  - setting: setting2\n" +
        "    environments:\n" +
        "      - name: env2.1\n" +
        "        value: 2.31\n" +
        "      - name: env2.2\n" +
        "        value: 2.12\n", MyYaml.class));

with output

MyYaml(settings=[
  Setting(name=setting2,
    environments=[Environment(name=env2.1, value=2),
                  Environment(name=env2.2, value=2)]),
  Setting(name=setting1,
    environments=[Environment(name=env1, value=31),
                  Environment(name=env2, value=12)])])

(Note: the lower case is only to avoid having to write down the rest of the fields, you can add them to be upper case)

josejuan
  • 9,338
  • 24
  • 31