klaxon icon indicating copy to clipboard operation
klaxon copied to clipboard

Failure parsing json into class with primary constructor with parameters not specifying var or val

Open gpaglia opened this issue 3 years ago • 0 comments

Hello,

A json fragment like the following:

{
    "aSymbol": "SYMBOL",
    "aType": 22
}    

cannot be parsed into any of the following kotlin clases (Example2 or Example3):

private class Example2(aSymbol: String, aType: Int) {
    val symbol = aSymbol
    val type = aType
}

or

class Example3(aSymbol: String, aType: Int) {
    val symbol: String
    val type: Int

    init {
        symbol = aSymbol
        type = aType
    }
}

while parsing into the following Example1 class will succeed:

private class Example1(val aSymbol: String, val aType: Int)

The parsing into Example2 or Example3 fail with a message like:

Unable to instantiate Example2:No argument provided for a required parameter: "parameter #0 aSymbol of fun (kotlin.String, kotlin.Int)

The parsing into Example2 or Example3 will succeed if a custom converter is configured.

If I understood correctly, Klaxon is supposed to use the primary constructor (or even secondary ones, possibly?) with their defined parameters to instantiate the required class, in this case then triggering the init logic that may be defined in field initializers or in the init block(s).

My environment:

  • Klaxon v5.5
  • Kotlin plugin v1.6.0
  • JVM v11
  • WIndows 10

Thanks for your support, GP

gpaglia avatar Jan 19 '22 11:01 gpaglia