How to serialize char/character data?

73 views
Skip to first unread message

Paulo Coutinho

unread,
Nov 3, 2022, 1:31:20 AM11/3/22
to google-gson
Hi,

I made a post on StackOverflow about how to serialize char/character data.

The serialization is working, but not the deserialization.

The complete post is here:

The code is:

private fun createGson(): Gson {
    val builder = GsonBuilder()

    val customCharSerializer = object : JsonDeserializer<Any?>, JsonSerializer<Char?> {
        override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext?): Any? {
            return try {
                Char(json.asJsonPrimitive.asInt)
            } catch (e: Exception) {
                null
            }
        }

        override fun serialize(src: Char?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement? {
            return src?.let { JsonPrimitive(it.code) }
        }
    }

    builder.registerTypeAdapter(Char::class.java, customCharSerializer,)
    builder.registerTypeAdapter(Character::class.java, customCharSerializer,)

    return builder.create()
}


The error is:
Expecting character, got: 122; at $.r.typeChar


Reply all
Reply to author
Forward
0 new messages