Search code examples
kotlinparsingserializationdeserialization

Convert stringified data class to data class Object Kotlin


I have a data class converted to string using

network.toString()

Result:

Network(addressRegex=^(0x)[0-9A-Fa-f]{40}$, memoRegex=, memo=false, network=ETH, enabled=true, withdrawMin=14.0, withdrawFee=7.03)

I want to convert it to Network Object, is there any way to do it?

data class Network( val addressRegex: String?,
                    val memoRegex: String?,
                    val memo: Boolean?,
                    val network: String)

Thanks!!

I could not do anything, as I did not find same problem on Internet


Solution

  • I am not sure what are your exact requirements, or the level of modification access you have to that log you extracted (it seems that the log and the Network data class you have are different). However, it's possible to parse what you have like so:

    data class Network(
        val addressRegex: String?,
        val memoRegex: String?,
        val memo: Boolean?,
        val network: String
    )
    
    val stringNetwork = "Network(addressRegex=^(0x)[0-9A-Fa-f]{40}$, memoRegex=, memo=false, network=ETH, enabled=true, withdrawMin=14.0, withdrawFee=7.03)"
    
    // Please note that this is a very naive/fragile approach...
    val network = stringNetwork
        .substringAfter("(")
        .split(",")
        .map { it.split("=") }
        .associate { it[0] to it[1] }
        .mapKeys { it.key.trim() }
        .mapValues { it.value.trim() }
        .let {
            Network(
                it[Network::addressRegex.name],
                it[Network::memoRegex.name],
                it[Network::memo.name]?.toBoolean(),
                (it[Network::network.name] ?: error("Network is required"))
            )
        }
    
    println(network)
    // => Network(addressRegex=^(0x)[0-9A-Fa-f]{40}$, memoRegex=, memo=false, network=ETH)
    

    However, I agree with @Tenfour04, if you have access to that Network object, it would be better to rely on a more concrete format/structure (i.e. JSON) and then safely deserialize / serialize it using a library like: kotlinx.serialization