Hello, I have a question regarding the retrieval ...
# apollo-kotlin
g
Hello, I have a question regarding the retrieval of JSON fields. I am in the context of data extraction from a GraphQL API. The data is read via Apollo-Kotlin before being stored in a BigQuery database. The API has a generic field that allows storing user data that may not be known in advance. This field is defined as being of JSON type. I want to retrieve the data without any transformation to process it later. Is it possible to retrieve the JSON string without any transformation? Any help is truly appreciated,
m
It depends how your json field is transmitted over the wire. Usually
JSON
custom scalars are transmitted like so:
Copy code
{
  "data": {
    "jsonField": {
      "key": "value"
    }
  }
}
In that case, you can use
AnyAdapter
to map it to a Kotlin
Any
that you can cast to
Map<String, Any?>
The other solution is if it's ttansmitted like so:
Copy code
{
  "data": {
    "jsonField": "{ \"key\": \"value\" }"
  }
}
(less common)
In that case, you can use
StringAdapter
to map it to a Kotlin
String
Actually you don't need to use
AnyAdapter
or
StringAdapter
because the runtime will do this by default and present you with an
Any
type that you can either cast to a
Map
or
String
If you want to serialize a
Map
back to JSON, you can use something like so:
Copy code
buildJsonString { 
    AnyAdapter.toJson(this, CustomScalarAdapters.Empty, map)
  }
But you have to parse the JSON in all cases because the parser needs to know where the JSON field stops
g
Thanks a lot Martin, I will try that.
👍 1