Hi everyone. Does kotlin multiplatform provide a w...
# multiplatform
m
Hi everyone. Does kotlin multiplatform provide a way to load a .json file? right now, I am sending the .json file as an argument from my android project and it works but it will be good if I can remove this dependency and put it solely in kotlin multiplatform.
t
m
I have used this already to parse the json. The problem is, in their examples they are using Data class but instead of that, I have a json file which I don't see on how I can use it directly instead of using the data class using kotlinx.serialization
t
just read the JSON file as you normally would, and use
JSON.parse(YourModel.serializer(), input)
a
@Mananpoddarm kotlinx.serialization doesn't work with data classes only. Although your JSON file is already modeled as data, and a data class would be grate. Assume, you have this json file
Copy code
{
  "name": "Mananpoddarm",
  "language": "kotlin",
  "platforms": [
    "js",
    "jvm",
    "native",
    "android"
  ]
}
You'll have to crate a class (a normal or a data class would do) like so
Copy code
@Serializable
class Model(
  val name:String,
  val language:String,
  val platforms: List<String>
)
And with serialization. Once you've read your json file, you can just go ahead and get your value like.
Copy code
val jsonString : String= readJsonFile("data.json");
val json = Json.parse(Model.serializer(),jsonString)
m
@andylamax readJsonFile() function is not defined in kotlinx serialization? what should I import to use this function in kotlin multiplatform? I am not able to find a way to read a json file in kotlin multiplatform is what I meant before.
@Tijl How to read json file normally in kotlin multiplatform? could you please share any resources because strangely, I couldn't find any resource or library which can help me in reading/writing on any file for that matter.
t
there’s no file access in the common API, so you do it on the platform side and pass a string or use a library
a
as @Tijl you'd have to expect/actual readJsonFile() andimplement it onall the platforms you target
269 Views