Wondering how to handle a situation where a untype...
# serialization
n
Wondering how to handle a situation where a untyped JSON array (always containing two items; first item Double, second item String) is returned as part of a HTTP response body.
The HTTP response body looks like this:
Copy code
{
  "status": "success",
  "data": {
    "resultType": "vector",
    "result": [
      {
        "metric": {
          "__name__": "cell_voltage",
          "battery": "1",
          "cell": "1",
          "exported_job": "cell_job",
          "instance": "xxxx:xxxx",
          "job": "push_gateway"
        },
        "value": [
          1584393298.147,
          "3366"
        ]
      },
// ...
    }
}
d
data class with two properties. Then write custom serializer?
n
Are you referring to the value field?
How will a custom serializer work with Array<Any>?
I have written my own custom serializer to handle the value field:
Copy code
@Serializable
internal data class CellVoltageValue(val timestamp: Double, val value: Int) {
    @Serializer(forClass = CellVoltageValue::class)
    internal companion object : KSerializer<CellVoltageValue> {
        override fun deserialize(decoder: Decoder): CellVoltageValue {
            val timestampPos = 0
            val valuePos = 1
            val input = decoder as? JsonInput ?: throw SerializationException("Expected Json Input")
            val array = input.decodeJson() as? JsonArray ?: throw SerializationException("Expected Json Array")
            val timestamp = array[timestampPos].primitive.double
            val value = array[valuePos].primitive.content.toInt()
            return CellVoltageValue(timestamp, value)
        }
    }
}
Handling mixed type arrays is missing from the KotlinX Serialization guide.
The custom class is referenced through this class (CellVoltageResultItem) which has the value field:
Copy code
@Serializable
internal data class CellVoltageResultItem(val metric: CellVoltageMetric, val value: CellVoltageValue)
In essence the value array has been turned into a object (accessed as a instance of a Kotlin Data Class) when it is deserialized.