-
Notifications
You must be signed in to change notification settings - Fork 666
Closed
Labels
Description
What is your use-case and why do you need this feature?
I have a class like that
data class MyClass2(
var id: Long,
var name: String,
var jsonData: String? = null
)Property jsonData for saving json object as string, jsonData can be any json object with different contents
When sending class to server, I want to have MyClass2 mapped to json like this:
{
"id":7,
"name":"Steve",
"jsonData":{
"someField1":true,
"someField2":4,
...
}
}I can't figure out how to achieve this. I was able to do other way around: deserialize json object field to my class string property. But struggle with serialization.
Describe the solution you'd like
In GSON I used to achieve this by making JsonStringFieldAdapter and annotation on property:
@JsonAdapter(JsonStringFieldAdapter::class)
var jsonData: String? = nullpublic class JsonStringFieldAdapter implements JsonSerializer<String>, JsonDeserializer<String> {
@Override
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return json.toString();
}
@Override
public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
return JsonParser.parseString(src).getAsJsonObject();
}
}I tried to make something similar with kotlinx.serialization
@Serializable(with = JsonAsStringSerializer::class)
var jsonData: String? = nullobject JsonAsStringSerializer: JsonTransformingSerializer<String>(tSerializer = String.serializer()) {
override fun transformDeserialize(element: JsonElement): JsonElement {
return JsonPrimitive(value = element.toString())
}
override fun transformSerialize(element: JsonElement): JsonElement {
return super.transformSerialize(element)
}
}Deserialization seems to be working, but I can't figure out how to do serialization