Emerson Cod
Emerson Cod

Reputation: 2090

Reading YAML with Jackson ignores keys without values

I have the following YAML file:

---
-
id: 001
start: 21.11.2018
additional:
dependency:
result: 2

which I like to read in with jackson as a simple List<Map<String, Object>>.

For this I use the following code

 private List<Map<String, Object>> readDefaultInputAsMap() {
    var objectMapper = new ObjectMapper(new YAMLFactory());
    objectMapper.setDateFormat(new SimpleDateFormat("dd.MM.yyyy"));
    try {
        return objectMapper.readValue(inputResource, new TypeReference<List<Map<String, Object>>>() {
        });
    } catch (IOException e) {
        e.printStackTrace();
        return new ArrayList<>();
    }
}

Unfortunately, this returns a map with only id, start and result, so the two others are ignored.

How can I get Jackson to parse the file and create the full map and with e.g. null as values for the empy keys ? (Or any other default value)?

Upvotes: 2

Views: 1215

Answers (2)

Bsquare ℬℬ
Bsquare ℬℬ

Reputation: 4487

You should create your own Object (new class) with all possible attributes you want, for instance:

 class MyCompleteInfo {
    String id;
    String start;
    String additional;
    String dependency;
    String result;
 }

And use a List of it (as method return, and in your reader):

List<MyCompleteInfo >

Edit: You may have used @JsonInclude(Include.NON_EMPTY) somewhere? You must not.

See documentation.

Upvotes: 1

madhead
madhead

Reputation: 33392

Actually, it does that by default. Double-check the format of your YML (because your example seems to be invalid). Here is what worked for me:

test.yml:

---
- id: 001
  start: 21.11.2018
  additional:
  dependency:
  result: 2

Test.java:

public class App {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        objectMapper.setDateFormat(new SimpleDateFormat("dd.MM.yyyy"));
        try {
            final Object value = objectMapper.readValue(App.class.getResource("test.yml"), new TypeReference<List<Map<String, Object>>>() {
            });

            System.out.println(value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And I got the result:

[{id=1, start=21.11.2018, additional=null, dependency=null, result=2}]

As you see, additional and dependency are both null.

Upvotes: 2

Related Questions