Serializing Operation.Data as JSON in Apollo 3 Android

Hello,

In the past we were able to use SimpleResponseWriter to serialize Operation.Data to a JSON string. In Apollo 3 that appears to have gone away but I’m seeing that Operation provides an Adapter and we have a toJson there which I think is the correct way to do this now. I have been trying to get this to work for me but can seem to get anything other than an empty string for json at the end.

Any help would be greatly appreciated. Here is a code example of what I’m doing.

val buffer = Buffer()
val writer = BufferedSinkJsonWriter(sink = buffer, indent = "  ")
operation.adapter().toJson(writer, CustomScalarAdapters.Empty, operationData)
val json = buffer.readUtf8()

I guess I really just want to make sure that this is the right way to go about this. And if not, what the right way would be. It’s definitely possible this is an issue on my end.

Update:

We’ve resolved the null issue. In our case the operation was nullable and the test case wasn’t properly set up after the migration.

I still wonder if this api is a 1 to 1 replacement for SimpleResponseWriter and marshaling the Operation.Data though so any insight there would still be appreciated.

Thanks so much,
Jeffrey

The code example above isn’t a perfect representation, turns out our operation was always null in a certain case which meant we we didn’t have an adapter which explains why the data wasn’t being serialized. Updated the question a bit.

Yep, that’s the way to do it. There’s an experimental buildJsonString that you can use too to save the hassle of creating a Buffer and then reading it. But for the most part you’re right.

If you’re on the JVM, there’s also a Operation.Data.toJson() so ultimately, you could go down to:

val json = buildJsonString {
  operationData.toJson(this)
}

But really, it’s doing the same thing that you’re doing already