I've got a question about deserializing a response...
# supabase-kt
c
I've got a question about deserializing a response that contains a column that is of type
json
Copy code
@Serializable
class Config(
    val type: String = "abc",
    val config: String = "", //this is json in postgres
)
If I try to select a config then I get this
Copy code
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 83: Expected beginning of the string, but got { at path: $[0].config
I kinda figured that the postgres json is just a string. Do I need to set it as something else?
Hm. Changing Config to
Copy code
@Serializable
class Config(
    val type: String = "abc",
    val config: JsonElement //this is json in postgres
)
worked. Honestly a little surprised as I could've sworn that when I worked with other apis that stuffed json into an api response for a specific field. id get a string back. I wonder what actually comes over the wire. anyway. wont worry about it now. but if anyone wants to shine some light on this ill take it.
j
The
json
type does send the data as actual JSON. So if you have a json object in your row, then it will be a JsonObject. Otherwise you'd just have a
text
column. So you can just use a generic
JsonElement
as your type or more precise a
JsonObject
or even a custom data class.
c
Very interesting... how does it send actual json if the response is already json? unless its not json? i guess ill try to use a proxy to inspect. And cool. I'll move to using a JsonObject... but I might consider just changing the field to text. 😃
j
You can print out the response data from
PostgrestResult#data
.
c
nice. thank you! TIL
wait. so how do i insert json data?
j
If you have a table
test
with a json column
example
, just do something like this:
Copy code
@Serializable
data class Test(val example: JsonObject)
Copy code
val toInsert = Test(buildJsonObject {
   put("key", "value")
})
supabase.from("test").insert(toInsert)
Or if the data in your json column is always following the same scheme, you can also use a custom data type:
Copy code
@Serializable
data class Test(val example: MyDataType) 

@Serializable
data class MyDataType(val key: String)
Copy code
val toInsert = Test(MyDataType("value"))
supabase.from("test").insert(toInsert)
Actually, there is also a documentation entry for that
❤️ 1
c
Interesting! thanks! I ended up using JsonElement for now and then
Copy code
Json.encodeToJsonElement(myObjectThatShouldBeConvertedToJson)
ah. and here i was looking at the kotlin docs page directly
j
Yea, the reference docs only document the methods etc. For Supabase/Postgres specific stuff, the main documentation shows a lot of examples and snippets
c
didn't know that either. will make sure to do that. thank you!