Is there a smarter way to deserialize the response...
# http4k
p
Is there a smarter way to deserialize the response body? I feel like I’m missing something 🙂
Copy code
val response = gqlClient(request).data.toString()
return ObjectMapper().readValue<RAArtistResponse>(response).data.artist
j
You can use a lens: https://www.http4k.org/guide/reference/json/ Something like...
Copy code
val raArtist = Body.auto<RAArtistResponse>().toLens()
val artist = raArtist(client(request))
s
Yes, the above is the way to go. You can also make the
.data.artist
part of the lens definition:
Copy code
Body.auto<RAArtistResponse>().map { it.data.artist }.toLens()
p
Sorry, I think I should’ve been more clear: It’s a GraphQL response and I’m not sure how to alter my lens to make it work with it:
d
@Philipp Mayer at the moment, there isn't really a better way - the data val of the response will be a Map. We don't currently generify on the output type when creating the handler - it's possible that we could do that. I'd maybe add an extension function to the response which contains your
Jackson.asA()
and takes the type arguments of the type you want out.... that should work I think for now
p
Alright, thanks for the explanation! This is totally fine for me, I was just curious if I overlooked something there. For now I just went with a normal http post, makes things way easier on my end for one single query.
d
Another option:
Copy code
fun Response.parseArtist() =
    objectMapper.readValue<RAArtistResponse>(data.toString()).data.artist
d
I think Jackson will have parsed it as a map on the conversion to any, so you don't have to call toString. It might not be readValue, but I'm sure there is a call which works in that api