mpw2
mpw2

Reputation: 67

Deserialise Yaml List of Objects

I have a yaml file with data that looks like this:

dog:
  animalId: dog00
  animalName: Dog
  animalFamily: Canidae
cat:
  animalId: cat00
  animalName: Cat
  animalFamily: Felidae
elephant:
  animalId: elpnt
  animalName: Elephant
  animalFamily: Elephantidae
...

(Update: I don't have control over the yaml file)

How can I deserialise this into a list of 'animal' objects in Java?

My Animal class looks like this

public class Animal {
   private String animalId;
   private String animalName;
   private String animalFamily;

   // getters, setters, constructors
}

I am trying to use jackson as follows

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Animal.class);

List<Animal> animals = mapper.readValue(new File("src/main/resources/animals.yaml"), listType);

but I get the error

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of 'java.util.ArrayList<Animal>' out of START_OBJECT token

Upvotes: 2

Views: 2912

Answers (1)

Martin Devillers
Martin Devillers

Reputation: 17992

Your YAML definition does not match your object model.

The YAML definition describes a Map of Animal, whereas your object model expects a List of Animal.

Try changing your YAML file to:

-
  animalId: dog00
  animalName: Dog
  animalFamily: Canidae
-
  animalId: cat00
  animalName: Cat
  animalFamily: Felidae
-
  animalId: elpnt
  animalName: Elephant
  animalFamily: Elephantidae

Or try changing your Java code so it deserializes to a Map<String, Animal>.

Map<String, Animal> animals = mapper.readValue(new File("src/main/resources/animals.yaml"), new TypeReference<Map<String, Animal>>(){});

Upvotes: 3

Related Questions