How to parse local JSON file in assets?

后端 未结 4 1602
灰色年华
灰色年华 2021-02-14 20:25

I have a JSON file in my assets folder. That file has one object with an array. The array has 150+ objects with each having three strings.

For each of these 150+ objects

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 21:00

    Previous answers work well, but if you're using Kotlin you can do it in a very nice and concise way by using the classes in the kotlin.io package.

    val objectArrayString: String = context.resources.openRawResource(R.raw.my_object).bufferedReader().use { it.readText() }
    val objectArray = Gson().fromJson(objectArrayString, MyObject::class.java)
    

    You could even turn into a nice generic extension method if you want for easy reuse:

    inline fun  Context.jsonToClass(@RawRes resourceId: Int): T =
            Gson().fromJson(resources.openRawResource(resourceId).bufferedReader().use { it.readText() }, T::class.java)
    

    Which you would then simply call like this:

    context.jsonToClass(R.raw.my_object)
    

提交回复
热议问题