When you just need a simple way to save an object as json to a human-readable file
android - Write JSON to a File - Stack Overflow
arrays - How get and use json from file with kotlin android? - Stack Overflow
android - How to read and write local JSON with kotlin - Stack Overflow
Videos
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();
}
});
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);
Place your json file under assets folder and read this as a String.
First, we need to create an extension to read the file. This extension takes file name as input.
fun AssetManager.readFile(fileName: String) = open(fileName)
.bufferedReader()
.use { it.readText() }
Now, use the extension to read the file as a String.
val jsonString = context.assets.readFile("file_name.json")
For more details you can look at this: https://github.com/ArtemBotnev/TelegramCharts/blob/master/app/src/main/java/ru/artembotnev/telegramcompetition/Repository.kt
The best way (IMHO) to read and write Json in Kotlin is Moshi:
- Declare a data class for each data structure you have in your file (you can use the json keys as field names).
- You might need to declare a global data class containing your data classes.
- Build a moshi instance.
- Get your data class moshi adapter.
- Use it to read the file.
More about how to use Moshi: https://github.com/square/moshi
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)
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/