Search code examples
javayamlmicronaut

How to use strings that contain special characters as keys in YAML with Micronaut


My application.yaml is like so:

env:
  emails:
    a: 0 # works, the rest don't
    b.com: 0
    c.com: 1
    "d.com": 0
    'e.com': 1
    "[f.com]": 0
    '[g.com]': 1

I am using this class to read it:

@ConfigurationProperties("env")
public class Configurator {
  private Map<String, Double> emails;

  public Map<String, Double> getEmails() {
    return emails;
  }

  public void setEmails(
      @MapFormat(keyFormat = StringConvention.RAW) Map<String, Double> emails) {
    this.emails = emails;
  }
}

Map emails only contains one entry: a : 0. How do I get keys that are strings containing special characters to map correctly?

I've already tried @MapFormat(keyFormat = StringConvention.RAW) in the setter function.

Alternatively, this application.yml format works for me - but I'm not sure how I can bind it directly to a Map<String, Double> using @ConfigurationProperties without using a TypeConverter.

env:
  emails:
    - key: a.com
    - value: 0

Solution

  • This won't work.

    env:
      emails:
        a: 0 
    

    will generate the key env.email.a with value 0. But

    env:
      emails:
        b.com: 0 
    

    will result in a different hierarchy key env.email.b.com with value 0. There is afaik no way to escape that since a . in a map always creates a child hierarchy.

    I recommend to change your configuration as you mentioned above.