Search code examples
scalajacksonjackson-dataformat-csv

Why is Jackson throwing a 'Cannot deserialize value of type `...` from Object value (token `JsonToken.START_OBJECT`)' when using with Scala?


I start with the following working code...

val source = scala.io.Source.fromFile(path)
val after = try source.mkString finally source.close()
val mapper: CsvMapper = new CsvMapper()
val it: MappingIterator[util.List[String]] =
  mapper.readerForListOf(classOf[String])
    .withFeatures(CsvParser.Feature.WRAP_AS_ARRAY)
    .readValues(after);
it.readAll().forEach(item => {
  println(item)
})

Now instead of a set of strings I want to use the first row as the headers and then map the other rows. I create my model object like...

@JsonIgnoreProperties(ignoreUnknown = true)
class ManagedUnit {
  @JsonProperty("Unit Name") val unitName: String = null
  def getUnitName(): String = unitName
}

And then try to change the parser...

val source = scala.io.Source.fromFile(path)
val after = try source.mkString finally source.close()
val mapper: CsvMapper = new CsvMapper()
val schema: CsvSchema =
  mapper.typedSchemaFor(classOf[ManagedUnit])
    .withHeader()
    .withColumnReordering(true)
val it: MappingIterator[ManagedUnit] =
  mapper.readerForListOf(classOf[ManagedUnit])
    .`with`(schema)
    .readValues(after);
it.readAll().forEach(item => {
  println(item)
})

But when I run I get...

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type java.util.ArrayList<com.purepm.data.model.appfolio.ManagedUnit> from Object value (token JsonToken.START_OBJECT)


Solution

  • readerForListOf should have been readerWithTypedSchemaFor