Skip to content

Instantly share code, notes, and snippets.

@imandaliya
Created May 30, 2024 07:46
Show Gist options
  • Save imandaliya/a26e5eef8a9e41b865537eb7d3ff2287 to your computer and use it in GitHub Desktop.
Save imandaliya/a26e5eef8a9e41b865537eb7d3ff2287 to your computer and use it in GitHub Desktop.
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
class GsonEx {
companion object {
inline fun <reified T> File.readModelFromFile(): T? {
var bufferReader: BufferedReader? = null
return try {
bufferReader = BufferedReader(FileReader(this))
Gson().fromJson(bufferReader, T::class.java)
} catch (e: IOException) {
e.printStackTrace()
null
} catch (e: JsonSyntaxException) {
e.printStackTrace()
null
} finally {
bufferReader?.close()
}
}
fun <T> T.writeModelToFile(file: File): Boolean {
return try {
val jsonString = Gson().toJson(this)
file.writeText(jsonString)
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment