Hi, I am working on a KMM library in which I have ...
# multiplatform
p
Hi, I am working on a KMM library in which I have one model class and now When I use the XCframework generated from the KMM library, I have a JSON string that I want to convert into my model class which is inside the XCFramework. But Swift doesn't allow that because of the Codable protocols. So how can I convert my JSON string to my model class in my swift iOS project?
d
Have you tried extending your model class in Swift to implement Codable (or just Decodable if you’re only interested in decoding an instance of your class from JSON)?
Copy code
extension YourKMMType: Decodable {
    init(from decoder: Decoder) throws {
        ...
    }
}
p
I have tried adding this init block
Copy code
public convenience init(from decoder: Decoder) throws {
    ...
}
But It didn't work. saying,
Copy code
Initializer requirement 'init(from:)' can only be satisfied by a 'required' initializer in the definition of non-final class 'SharedModel'
d
You’ll probably need to remove the
convenience
keyword.
p
No, it has to be
convenience init
because the designated initializer cannot be declared in an extension.
d
Ah. I don’t have the time right now to play with this myself, but you could try to let Kotlin export the class as final.
p
Sure, I will give it a try.
d
If that doesn’t work out, you can always fall back on JSONSerialization and its jsonObject method. This will transform JSON to nested dictionary/array/number/string… objects that you can then process however you like, for example by creating new SharedModel objects and filling them with the data from jsonObject’s output. You’ll do lots of casting though…
p
Thanks for the info.