Skip to content

Serialize string property as json object #2072

@ArtemMikhaylov

Description

@ArtemMikhaylov

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? = null
public 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? = null
object 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions