Reputation: 2391
I use the Apollo Android library to make queries to a GraphQL endpoint. Everything works OK until I try to convert the results back to JSON strings (to store them in a Room database). I naively tried to use Moshi, however this fails with the following error:
Cannot get available extra products: No JsonAdapter for interface com.example.MyQuery$MyFragmentInterface
where MyFragmentInterface
in an interface generated by Apollo to handle query fragments.
So, I tried to find whether the Apollo library has/generates any conversion methods, i.e. sth like toJson()
/fromJson()
, for the generated models, however I couldn't find anything usable.
Am I missing something obvious?
Upvotes: 15
Views: 4026
Reputation: 2391
Since Apollo 1.3.x there is an Operation.Data.toJson()
extension function (Kotlin) and a corresponding serialize
static method in Java.
Check https://www.apollographql.com/docs/android/advanced/no-runtime/#converting-querydata-back-to-json
For the opposite, Json string to Query.Data
, I use something like the following:
import okio.Buffer
fun String?.toMyData(): MyQuery.Data? {
this ?: return null
val query = MyQuery()
val response: Response<MyQuery.Data> =
OperationResponseParser(query,
query.responseFieldMapper(),
ScalarTypeAdapters.DEFAULT)
.parse(Buffer().writeUtf8(this))
return response.data
}
Upvotes: 6
Reputation: 2719
Here is an example how you can deserialize string as generated object. Inlined comments for further details.
// Sample string response
val jsonResponse = """
{
"data": {
{
"id": "isbn-889-333",
"title": "Awesome title",
"rating": 5
}
}
""".trimIndent()
// Create query that is expect to return above response
val query = QueryBookDetails("book_id")
// convert string to input stream
val inputStream = ByteArrayInputStream(jsonResponse.toByteArray())
// Read bytes into okio buffer
val buffer = Buffer().readFrom(inputStream)
// Use the query to parse the buffer.
val response = query.parse(buffer)
// response.data might be the one needed by you
Bear in mind that the response must honour the schema.
Upvotes: 2
Reputation: 9432
Try Postman
and see if the error also appears there https://blog.getpostman.com/2019/06/18/postman-v7-2-supports-graphql/
Upvotes: 0