Kotlin: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 8: | Line 8: | ||
) | ) | ||
==Writing to Gson== | ==Reading and Writing to Gson== | ||
Given the following | |||
var mySportsActivity = SportsActivity( | var mySportsActivity = SportsActivity( | ||
Line 20: | Line 22: | ||
val json = gson.toJson(mySportsActivity) | val json = gson.toJson(mySportsActivity) | ||
FileWriter("D:\\IAIN\\Output.json").use { | var filename = "D:\\IAIN\\Output.json"; | ||
You can write to a file with | |||
FileWriter(filename).use { | |||
writer -> | |||
val gson = GsonBuilder().create() | |||
gson.toJson(mySportsActivity, writer) | |||
} | |||
And read it back with | |||
FileReader("D:\\IAIN\\Output.json").use { | |||
reader -> | |||
val gson = GsonBuilder().create() | val gson = GsonBuilder().create() | ||
gson. | mySportsActivity2 = gson.fromJson(reader,SportsActivity::class.java) | ||
} | } |
Revision as of 05:07, 15 January 2018
Data Class
data class SportsActivity ( val totalAveragePaceInMinutesPerKilometre: Double, val totalAverageSpeedInKilometresPerHour: Double, val totalDurationInSeconds: Int, val totalAverageDistanceInMetres: Double, var dateOfActivity: Date )
Reading and Writing to Gson
Given the following
var mySportsActivity = SportsActivity( 0.0, 0.0, 0, 0.0, Date())
val gson = Gson() val json = gson.toJson(mySportsActivity)
var filename = "D:\\IAIN\\Output.json";
You can write to a file with
FileWriter(filename).use { writer -> val gson = GsonBuilder().create() gson.toJson(mySportsActivity, writer) }
And read it back with
FileReader("D:\\IAIN\\Output.json").use { reader -> val gson = GsonBuilder().create() mySportsActivity2 = gson.fromJson(reader,SportsActivity::class.java) }