Reputation: 769
My objectmapper.readValue() function throws an error that says "Cannot construct instance of MyErrorMessage
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value."
What's wrong with my MyErrorMessage class that makes objectmapper fail?
This is the JSON I'm trying to parse.
{
"meta": {
"id": "43225a4853b5497a",
"time": "2020-06-03T13:36:03.391814Z"
},
"datadetail": {
"aKey": "hweriu-erw",
"aTypes": [
{
"bKey": "ewrf-7e9f",
"cKey": "12ddf3",
"status": "ERROR",
"errorMessage": {
"message": "Not found"
}
}
],
"status": "ONE",
"errorMessage": "ERROR with aKey"
}
}
This is the function and the classes.
private fun ParseResponse(responseMessage: String): MyResponse{
try {
val objectMapper = ObjectMapper()
return objectmapper.readValue(message, MyResponse::class.java)
}catch (e: JsonProcessingException) {
throw IllegalArgumentException("json was invalid $responseMessage", e)
}
}
data class MyResponse(
val meta: Metainfo,
val datadetail: DataResponse
)
data class MetaInfo(
val id: String,
val time: Instant
)
data class DataResponse(
val aKey: MyKey,
val aTypes: List<TypesResponse>,
val aNumber: String? = null,
val status: StatusType,
val errorMessage: MyErrorMessage = null
)
enum class StatusType{
OK,
ERROR
}
data class TypesResponse(
val bKey: MyBKey,
val cKey: MyCKey,
val status: StatusType,
val errMessage: MyErrorMessage? = null
)
data class MyErrorMessage(
@JsonProperty("message")
val message: String,
@JsonProperty("context")
val context: MyContext?,
){
constructor(message: String) : this(
message = message,
context = null
)
enum class MyContext{
ONE, TWO, THREE
}
}
Upvotes: 0
Views: 1593
Reputation: 17510
Your JSON does not follow your class structure.
You have "errorMessage": "ERROR with aKey"
, but your errorMessage
in DataResponse
is in fact a MyErrorMessage
which is an object, not a simple String.
It would need to be:
"errorMessage": {
"message": "ERROR with aKey"
}
If that is not an option, then you need a custom Jackson JSON Deserializer for your MyErrorMessage
that can handle that. You can check an example here.
Upvotes: 2