CoderUni
CoderUni

Reputation: 6144

How to insert Json Object inside Json Array in Kotlin using gson

I am new in using gson. I have tried several times to insert a Json Object inside a Json Array in Kotlin. I was able to successfully create the Json Array with Json Object and save it to internal storage. However, I wasn't able to insert Json Object inside it with this code. Any suggestions on how I would be able to achieve this? I've tried to get the file from internal storage and I couldn't fromJson it so I'm not sure if this idea would work. The data in the array are all strings. Here is my code:

    fun save(){
        var gson = Gson()
        val filename = "name"
        val file = context?.getFileStreamPath(filename)
        if(file == null || !file.exists()){
            val array= ArrayList<arraylist>()
            array.add(arraylist("1","2","3"))
            var json:String=gson.toJson(array).replace("\\n", "\n")
            context?.openFileOutput(filename, Context.MODE_PRIVATE).use {
                it?.write(json.toByteArray())
            }
        }
        else{
            val file = File(context?.filesDir, filename)
            val contents = file.readText()
            val gson = GsonBuilder().create()
            val content = gson.fromJson(contents, arraylist::class.java)
            content.add(arraylist("1","2","3"))
            var json:String=gson.toJson(content).replace("\\n", "\n")
        }
    }

Upvotes: 1

Views: 5458

Answers (1)

CoderUni
CoderUni

Reputation: 6144

I finally fixed this by reading it then saving it to internal storage. This is inside the else{} statement:

    val file1 = File(context?.filesDir, filename)
    val contents = file1.readText()
    val array = gson.fromJson(contents, Array<arraylist>::class.java)
    val arrayList = ArrayList(array.toMutableList())
    arrayList.add(devices("Finally","Works","Wow"))
    val json: String = gson.toJson(arrayList).replace("\\n", "\n")
    context?.openFileOutput(filename, Context.MODE_PRIVATE).use {
        it?.write(json.toByteArray())
    }

Upvotes: 2

Related Questions