Created
May 30, 2024 07:46
-
-
Save imandaliya/a26e5eef8a9e41b865537eb7d3ff2287 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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