wykopowiedz
wykopowiedz

Reputation: 91

How to create Map from yaml file with Jackson?

This is the class:

public class YamlMap {

    Map<String, String> mp = new HashMap<>();

    String get(String key) {
        return this.mp.get(key);
    }
}

and this is the props.yml:

mp:
  key1: ok
  key2: no

When I run:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.findAndRegisterModules();
YamlMap ym2 = mapper.readValue(new File("src/main/resources/props.yml"), YamlMap.class);

then I get error:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "YamlMap" (class YamlMap)

Upvotes: 2

Views: 7645

Answers (1)

Michał Krzywański
Michał Krzywański

Reputation: 16900

A quick solution is to add @JsonProperty("mp") above your field :

public class YamlMap {

    @JsonProperty("mp")
    Map<String, String> mp;
}

Jackson core annotation names might be misleading but even though this annotation has Json in its' name - it will work. Jackson can be configured to parse different formats like Yaml or CBOR - but still for mapping you would use core annotations which have Json in their names.

Another solution is to create a constructor and use @JsonCreator :

public class YamlMap {

    Map<String, String> mp;

    @JsonCreator
    public YamlMap(@JsonProperty("mp") Map<String, String> mp) {
        this.mp = mp;
    }
}

Upvotes: 3

Related Questions