Search code examples
spring-bootkotlinresttemplate

Calling Rest Endpoint with RestTemplate and Kotlin Data Class


trying to call a rest endpoint which returns a simple json but i fail all the time.

The Result looks like that:

{
  "Products": [
    {
      "Name": "ABC",
      "Guid": "4711"
    },
    {
      "Name": "DEF",
      "Guid": "9876"
    },
    {
      "Name": "HGT",
      "Guid": "159"
    }
  ]
}

My Code like that:

override fun getProductMetaList(): List<BestProductMetaInfo> {
    val url = "https://$baseUrl/api/meta"
    return this.getForObject(url, GetProductMetaListResult::class.java)?.Products ?: emptyList()
}

...

@JsonIgnoreProperties(ignoreUnknown = true)
data class GetProductMetaListResult(
        @JsonProperty("Products")
        var Products: List<ProductMetaInfo> = emptyList()
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class ProductMetaInfo(
        @JsonProperty("Guid")
        var Guid: String = "",
        @JsonProperty("Name")
        var Name: String = ""
)

And the result always:

nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of GetProductMetaListResult (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value

I tried using default values and nullable value, but everything results the same.


Solution

  • As Your API response is started with {, It's a JSON object. But you are trying to convert it as List as a result Exception occured.

    First Parse it as JSON object and then get list from its result.