Skip to content

Instantly share code, notes, and snippets.

View hissain's full-sized avatar
:atom:

Md. Sazzad Hissain Khan hissain

:atom:
View GitHub Profile
val list = listOf(Student(), Student() ... )
val gson = Gson()
val jsonString = gson.toJson(list)
val sType = object : TypeToken<List<Student>>() { }.type
val otherList = gson.fromJson<List<Student>>(jsonString, sType)
val list = listOf("String1", "String2" ... )
val gson = Gson()
val jsonString = gson.toJson(list)
val sType = object : TypeToken<List<String>>() { }.type
val otherList = gson.fromJson<List<String>>(jsonString, sType)
val gSon = GsonBuilder().registerTypeAdapter(Student::class.java, StudentSerializer()).create()
val json = gSon.toJson(student)
class StudentSerializer : JsonSerializer<Student> {
override fun serialize(src: Student?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
val jsonObject = JsonObject()
try {
jsonObject.add("name", context?.serialize(src.name))
jsonObject.add("address", JsonParser().parse(src.address))
val gSon = GsonBuilder().registerTypeAdapter(Student::class.java, StudentDeserializer()).create()
val student = gSon.fromJson<Student>(json2, Student::class.java)
/** Output student will be like below **/
student.name // Mark
student.address // { "city": "London", "post": "12000" }
data class Student(
var name: String? = null,
var address: String? = null) {
}
class StudentDeserializer : JsonDeserializer<Student> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Student {
json as JsonObject
val name = json.get("name").asString
val json2 = """
{
"name": "Mark",
"address": {
"city": "London",
"post": "12000"
}
} """
data class Address(
var city: String? = null,
var post: String? = null) {
}
data class Student(
var name: String? = null,
var address: Address? = null) {
}
val json = """
{
"name": "Alex",
"address": {
"city": "Rome",
"post": "1000"
}
} """
data class Student(
@SerializedName("key_name")
var name: String? = null,
@SerializedName("key_address")
var address: String? = null) {
}
val student = Student("Mark", "London, 12000") // object
val json = Gson().toJson(student) // json string