🌐
BezKoder
bezkoder.com › home › ways to write to file in kotlin
Ways to write to File in Kotlin - BezKoder
January 24, 2024 - If you want to make pretty JSON string, GsonBuilder will help you. Let’s do it right now. package com.bezkoder.kotlin.writefile import java.io.File import com.google.gson.Gson import com.google.gson.GsonBuilder fun main(args: Array<String>) { val tutsList: List<Tutorial> = listOf( Tutorial("Tut #1", "bezkoder", listOf("cat1", "cat2")), Tutorial("Tut #2", "zkoder", listOf("cat3", "cat4")) ); val gson = Gson() val jsonTutsList: String = gson.toJson(tutsList) File("bezkoder1.json").writeText(jsonTutsList) val gsonPretty = GsonBuilder().setPrettyPrinting().create() val jsonTutsListPretty: String = gsonPretty.toJson(tutsList) File("bezkoder2.json").writeText(jsonTutsListPretty) }
🌐
Techie Delight
techiedelight.com › home › java › write json to a file in kotlin
Write JSON to a file in Kotlin | Techie Delight
2 weeks ago - The idea is to create a PrintWriter instance and call its write() function to write the JSON string. To write to a file, construct a FileWriter using the platform’s default character encoding.
Discussions

When you just need a simple way to save an object as json to a human-readable file
I'm struggling to see how it's useful at all🙄 It's like a line of code to serialise an object to it's string representation with something like gson that's crazy well established and then file operations aren't exactly a huge burden either... What am I missing? More on reddit.com
🌐 r/Kotlin
13
9
March 22, 2024
android - Write JSON to a File - Stack Overflow
I have a class compositionJSON. The class has a method calls makeJSONObject, that creates a JSON-Object and put stuff in it. Here is the code of the class. public class CompositionJso extends JSON... More on stackoverflow.com
🌐 stackoverflow.com
arrays - How get and use json from file with kotlin android? - Stack Overflow
I have tried to get and use json from file in Kotlin-lang in Android but this is not so easy as I thought! More on stackoverflow.com
🌐 stackoverflow.com
android - How to read and write local JSON with kotlin - Stack Overflow
I followed a tutorial to setup reading JSON file from assets and parsing using GSON. This is all works well, but I want the user to also be able to edit the json file by making changes in the app. ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › nplix › how-to-read-and-write-json-data-in-kotlin-with-gson-c2971fd2d124
How to Read and Write JSON data in Kotlin with GSON | by Pawan Kumar | NPLIX | Medium
January 8, 2018 - So here in this tutorial we are going to learn about how to read and write GSON data in Kotlin. If you would like learn the java version of this tutorial check out the last tutorial “How to Read and Write JSON data using GSON”. In this tutorial we will write two method. In first method we will create a JSON file and in second method we will read the file and and print in a text box.
🌐
Reddit
reddit.com › r/kotlin › when you just need a simple way to save an object as json to a human-readable file
r/Kotlin on Reddit: When you just need a simple way to save an object as json to a human-readable file
March 22, 2024 - And if Java wouldn't have been a priority and you'd want to have it Kotlin only, then it would really be useless because since you have to annotate your classes anyway, why...not use @Serializable from kotlinx-serialization? If you use nested data classes you shouldn't have to write almost any custom serializers. And then you could replace this external dependency with two oneliners: inline fun <reified T: Any> File.write(value: T) = Json.encodeToString<T>(value).let(::writeText) inline fun <reified T: Any> File.read() = Json.decodeFromString<T>(readText()) @Serializable data class Something(val id: String, val name: String) fun main() { val value = Something("1", "one") val file = File("/tmp/somethings.json") file.write(value) check(value == file.read<Something>()) }
🌐
Nplix
nplix.com › 2017 › 12 › how-to-read-and-write-json-data-in.html
How to Read and Write JSON data in Kotlin with GSON
December 26, 2017 - For writing the JSON data to file in Kotlin, we need to deal with file handling to write the JSON data into the file. In this example, we are creating the file into cache location.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-in-kotlin-with-jackson
Reading and Writing JSON in Kotlin with Jackson
February 27, 2023 - In this tutorial, we've gone over how to read and write JSON Files in Kotlin with Jackson.
🌐
CodeSignal
codesignal.com › learn › courses › handling-json-files-with-kotlin-2 › lessons › working-with-json-in-kotlin-using-jackson
Working with JSON in Kotlin Using Jackson
In this lesson, you've gained skills in constructing and writing JSON data using Kotlin. We began with simple objects, expanded into complex structures involving collections, and wrote the data to a file in a clearly formatted manner.
Top answer
1 of 4
12

makeJSONObject is returning JSONObject

Your code should be

saveCompo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setName();
            createJSONFolder();
            CompositionJso obj = new CompositionJso();
            JSONObject  jsonObject = obj.makeJSONObject(compoTitle, compoDesc, imgPaths, imageViewPaths);
            MyCompositionsListActivity.buildList();

            try {
                Writer output = null;
                File file = new File("storage/sdcard/MyIdea/MyCompositions/" + compoTitle + ".json");
                output = new BufferedWriter(new FileWriter(file));
                output.write(jsonObject.toString());
                output.close();
                Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
            finish();
        }
    });
2 of 4
3

Try this write a simple class with static methods to save and retrieve json object in a file :

CODE :

public class RetriveandSaveJSONdatafromfile {

 public static String objectToFile(Object object) throws IOException {
    String path = Environment.getExternalStorageDirectory() + File.separator + "/AppName/App_cache" + File.separator;
    File dir = new File(path);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    path += "data";
    File data = new File(path);
    if (!data.createNewFile()) {
        data.delete();
        data.createNewFile();
    }
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
    objectOutputStream.writeObject(object);
    objectOutputStream.close();
    return path;
}

public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
    Object object = null;
    File data = new File(path);
    if(data.exists()) {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
        object = objectInputStream.readObject();
        objectInputStream.close();
    }
    return object;
}
} 

To save json in a file use RetriveandSaveJSONdatafromfile.objectToFile(jsonObj) and to fetch data from file use

 path = Environment.getExternalStorageDirectory() + File.separator +   
 "/AppName/App_cache/data" + File.separator; 
 RetriveandSaveJSONdatafromfile.objectFromFile(path);
Find elsewhere
🌐
YouTube
youtube.com › watch
Android Kotlin Usage Tutorial #082 - JSON,save to file - YouTube
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new featuresNFL Sunday Ticket · © 2025 Google LLC
Published   January 28, 2018
🌐
Android Developers
developer.android.com › api reference › jsonwriter
JsonWriter | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › writing to a file in kotlin
Writing to a File in Kotlin | Baeldung on Kotlin
April 28, 2026 - The method writeBytes takes a ByteArray as an argument and directly writes it into the specified file. This is useful when we have the contents as an array of bytes rather than plain text.
🌐
Sling Academy
slingacademy.com › article › how-to-read-and-write-json-files-in-kotlin
How to Read and Write JSON Files in Kotlin - Sling Academy
Here, you serialize the object to a JSON string and write it to a file using Kotlin's writeText method.
🌐
Kotlin
kotlinlang.org › docs › tutorials › kotlin-for-py › file-io.html
File I/O - Kotlin Programming Language
You can write binary data to a file by calling outputStream() on a file object and use the resulting OutputStream to write bytes.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
How to write JSON to a file using Moshi - Java Code Geeks
June 20, 2024 - Add Moshi to your project dependencies (com.squareup.moshi:moshi:1.13.0 and com.squareup.moshi:moshi-kotlin:1.13.0). Create a Java class to represent the data structure. Use Moshi to serialize the Java object to JSON and write it to a file.
🌐
Kodeco
kodeco.com › android › paths › multiscreen-app › 44884662-save-user-state › 03-read-write-files › 03
Read & Write Files, Episode 16: Read & Write Files in Internal Storage | Kodeco
Nzuj af xeq toif kheyl vocf peid: import android.content.Context import com.kodeco.android.devscribe.data.local.NoteEntity import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.io.File import java.io.IOException class InternalNotesFileManager( private val context: Context ) { fun writeTextFile(note: NoteEntity) { val directory = File(context.filesDir, DIRECTORY_NAME) if (!directory.exists()) { directory.mkdirs() } val file = File(directory, "${note.title}.txt") try { file.outputStream().use { outputStream -> outputStream.write(Json.encodeToString(note).toByteArray()) } } catch (e: IOException) { e.printStackTrace() } } companion object { const val DIRECTORY_NAME = "DevScribeNotesInternal" } }
Top answer
1 of 3
31

In 2019 no-one is really parsing JSON manually. It's much easier to use Gson library. It takes as an input your object and spits out JSON string and vice-versa.

Example:

data class MyClass(@SerializedName("s1") val s1: Int)

val myClass: MyClass = Gson().fromJson(data, MyClass::class.java)
val outputJson: String = Gson().toJson(myClass)

This way you're not working with JSON string directly but rather with Kotlin object which is type-safe and more convenient. Look at the docs. It's pretty big and easy to understand

Here is some tutorials:

  • https://www.youtube.com/watch?v=f-kcvxYZrB4
  • http://www.studytrails.com/java/json/java-google-json-introduction/
  • https://www.tutorialspoint.com/gson/index.htm

UPDATE: If you really want to use JSONObject then use its constructor with a string parameter which parses your JSON string automatically.

val jsonObject = JSONObject(data)
2 of 3
11

Best way is using kotlinx.serialization. turn a Kotlin object into its JSON representation and back marking its class with the @Serializable annotation, and using the provided encodeToString and decodeFromString<T> extension functions on the Json object:

import kotlinx.serialization.*
import kotlinx.serialization.json.*
​
@Serializable
data class User(val name: String, val yearOfBirth: Int)
​
   // Serialization (Kotlin object to JSON string)
​
   val data = User("Louis", 1901)
   val string = Json.encodeToString(data)
   println(string) // {"name":"Louis","yearOfBirth":1901}
​
   // Deserialization (JSON string to Kotlin object)
​
   val obj = Json.decodeFromString<User>(string)
   println(obj) // User(name=Louis, yearOfBirth=1901)

Further examples: https://blog.jetbrains.com/kotlin/2020/10/kotlinx-serialization-1-0-released/

🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.js › -j-s-o-n
JSON - Kotlin Programming Language
July 13, 2023 - Try the revamped Kotlin docs design! ... Exposes the JavaScript JSON object to Kotlin.
🌐
Delasign
delasign.com › blog › android-studio-kotlin-json
How to add a JSON file to an Android Studio project
June 13, 2023 - Write the name of your file (i.e. sample.json) in the pop up and press Enter. Follow the relevant tutorial below to learn how to consume and use JSON data in Kotlin and Android Studio.How to read a JSON file from the assets folder using KotlinHow to convert a JSON into usable data in Kotlin