[AOS] Gson, Json convert

2024. 1. 18. 13:45dev/aos

728x90
반응형

language : kotlin

 

library

dependencies {
    // neander
    // implementation("com.github.donguran:NLog:1.1.3")

    // gson library
    implementation 'com.google.code.gson:gson:2.10.1'
}

 

 

 

Gson convert Json

val gson:Gson = Gson()
val loginModel:WebLoginModel = gson.fromJson(response.toString(), WebLoginModel::class.java)

 

 

data class model

@SerializedName : mapping json to property.

import com.google.gson.annotations.SerializedName

data class WebLoginModel(
    var login: String = "",
    @SerializedName("mem_seq") var mem_seq: String = "",
    var mem_type1: String = "",
    var mem_type2: String = "",
    var mem_id: String = "",
    var mem_name: String = "",
    var mem_email: String = "",
    var sns_auth_url: String?,
) {
    fun isEmpty(): Boolean = (
        mem_seq.isEmpty() &&
        mem_type1.isEmpty() &&
        mem_type2.isEmpty() &&
        mem_id.isEmpty() &&
        mem_name.isEmpty() &&
        mem_email.isEmpty()
    )
}

 

 

return values number(Interger) or ""(Empty)

com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: empty String
import com.google.gson.JsonObject
import com.google.gson.JsonParser

val jsonString = "{ \"mem_seq\": \"5147\", \"mem_type1\": \"type1\", \"mem_type2\": \"type2\", \"mem_id\": \"id\", \"mem_name\": \"name\", \"mem_email\": \"email\", \"sns_auth_url\": null }"

val jsonParser = JsonParser()
val jsonObject = jsonParser.parse(jsonString).asJsonObject

val memSeqString = jsonObject.get("mem_seq")?.asString ?: ""
val memSeq: Int? = try {
    memSeqString.toInt()
} catch (e: NumberFormatException) {
    null
}

val webLoginModel = WebLoginModel(
    login = "",
    mem_seq = memSeq,
    mem_type1 = jsonObject.get("mem_type1")?.asString ?: "",
    mem_type2 = jsonObject.get("mem_type2")?.asString ?: "",
    mem_id = jsonObject.get("mem_id")?.asString ?: "",
    mem_name = jsonObject.get("mem_name")?.asString ?: "",
    mem_email = jsonObject.get("mem_email")?.asString ?: "",
    sns_auth_url = jsonObject.get("sns_auth_url")?.asString
)
728x90
반응형

'dev > aos' 카테고리의 다른 글

[AOS] Firebase Crashlytics  (0) 2024.01.19
[AOS] WebView  (0) 2024.01.19
[AOS] Coroutine  (0) 2024.01.18
[AOS] HttpUrlConnection  (0) 2024.01.18
[AOS] Android14  (0) 2024.01.16