I'm getting an InvalidDefinitionException on parsing json into my own custom class.
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid type definition for type id.or.jisedu.repo.Book: Argument #0 of constructor [constructor for id.or.jisedu.repo.Book, annotations: [null]] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
at [Source: (String)"…"
Here is the line which is causing issues:
val wrapper: BookWrapper = mapper.reader().forType(BookWrapper::class.java).readValue("""
{
"book": {
"publisher": "Pearson",
"image": "https:\/\/images.isbndb.com\/covers\/34\/13\/9780134093413.jpg",
"title_long": "Campbell Biology (11th Edition)",
"edition": "11",
"date_published": "2016-10-29",
"authors": [
"Lisa A. Urry",
"Michael L. Cain",
"Steven A. Wasserman",
"Peter V. Minorsky",
"Jane B. Reece"
],
"title": "Campbell Biology (11th Edition)",
"isbn13": "9780134093413",
"binding": "Hardcover",
"publish_date": "2016-10-29",
"isbn": "0134093410"
}
}""")
And here is my bookwrapper class:
data class BookWrapper(@JsonProperty("book") val book: Book)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class Book(
val title: String,
@JsonProperty("title_long")
val titleLong: String? = null,
val isbn: String? = null,
val isbn13: String? = null,
val dewey_decimal: String? = null,
val format: String? = null,
val publisher: String? = null,
val publish: String? = null,
val language: String? = null,
@JsonProperty("date_published")
val datePublished: String? = null,
@JsonProperty("publish_date")
val publishDate: String? = null,
val edition: String? = null,
val pages: String? = null,
val binding: String? = null,
val dimensions: String? = null,
val overview: String? = null,
val excerpt: String? = null,
val synopsys: String? = null,
val image: String? = null,
val authors: List<String>,
val subjects: List<String>? = null,
var id: Long? = null,
var amount: Int = 1
)
EDIT:
I forgot to register the KotlinModule. Don't forget to do that.
Yes, registering KotlinModule helps. To register Kotlin module:
Add dependency to build.gradle:
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8")
Create ObjectMapper:
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
val mapper = jacksonObjectMapper()
More information at https://www.baeldung.com/kotlin/jackson-kotlin
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With