일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 알고리즘
- notification
- Coroutine
- onLayout
- 알림
- kotlin
- HTTP
- lifecycle
- Navigation
- Behavior
- CustomView
- onMeasure
- 안드로이드
- activity
- View
- Algorithm
- LiveData
- 코틀린
- BOJ
- DataBinding
- CoordinatorLayout
- Android
- 백준
- AppBarLayout
- recyclerview
- sqlite
- room
- hilt
- CollapsingToolbarLayout
- ViewModel
- Today
- Total
개발일지
Kotlin in A..Z - Gson 본문
Gson
Json을 Serialize, Deserialize를 돕는 라이브러리입니다. Gson을 통해 Object와 Json을 쉽게 직렬화, 역직렬화 할 수 있고 다양한 옵션을 제공하기 때문에 상황에 맞게 Strategy를 설정할 수 있습니다.
Class
data class LoginForm(
@SerializedName(value = "id", alternate = ["clientId", "userId"])
val id: String? = null,
@SerializedName(value = "password", alternate = ["clientPassword", "userPassword"])
val password: String? = null
)
data class Profile(
val name: String? = null
)
data class User(
val loginForm: LoginForm? = null,
val profile: Profile? = null
) {
@Transient
private val secret: String = "Secret"
}
Gson 생성
Gson을 사용하기 위해서 일단 Gson 객체를 만들어야 합니다. GsonBuilder를 사용하여 다양한 설정을 할 수 있고, Gson으로 바로 생성할 수 있습니다.
val gson: Gson = GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
.create()
val gson = Gson()
Serialize
Object를 Json으로 바꾸는 방법입니다. Gson.toJson으로 쉽게 바꿀 수 있습니다.
fun serialize() {
val user = User(
LoginForm("rkdxowhd98", null),
Profile("강태종")
)
gson.toJson(user).also {
println(it)
}
}
{
"loginForm": {
"id": "rkdxowhd98",
"password": null
},
"profile": {
"name": "강태종"
}
}
Deserialize
Json을 Object로 바꾸는 방법입니다. Gson.fromJson을 사용하여 쉽게 바꿀 수 있습니다.
fun deserialize() {
val json = "{\"loginForm\":{\"id\":\"rkdxowhd98\",\"password\":\"123123\"},\"profile\":{\"name\":null}}"
gson.fromJson(json, User::class.java).also {
println(it)
}
}
User(loginForm=LoginForm(id=rkdxowhd98, password=123123), profile=Profile(name=null))
Collection
Collection(Map, List, Array, Set 등)을 직렬화하고 역직렬화 하는 방법입니다.
fun collection() {
val json = gson.toJson(listOf(
User(LoginForm("rkdxowhd98@naver.com", "123123"), Profile("Naver")),
User(LoginForm("rkdxowhd98@kakao.com", "123123"), Profile("Kakao"))
))
gson.fromJson<List<User>>(json, object : TypeToken<List<User>>() {}.type).also {
println(it)
}
}
setPrettyPrinting()
Json으로 직렬화할 때 보기 좋게 출력합니다.
Before
{"loginForm":{"id":"rkdxowhd98","password":null},"profile":{"name":"강태종"}}
After
{
"loginForm": {
"id": "rkdxowhd98",
"password": null
},
"profile": {
"name": "강태종"
}
}
serializeNulls()
null값을 직렬화/역직렬화 합니다. (역직렬화 할 때 값을 null이면 기본값을 사용한다.)
Before
{
"loginForm": {
"id": "rkdxowhd98"
},
"profile": {
"name": "강태종"
}
}
After
{
"loginForm": {
"id": "rkdxowhd98",
"password": null
},
"profile": {
"name": "강태종"
}
}
excludeFieldsWithModifiers()
Modifiers에 따라 직렬화 필드를 제외할 수 있다.
* @Transient을 사용하여 이 함수를 호출하지 않고 제외할 수 있다.
excludeFieldsWithModifiers(
Modifier.TRANSIENT, Modifier.PRIVATE
)
setFieldNamingPolicy()
Policy에 따라 직렬화/역직렬화 시 이름 짓는 규칙을 바꿀 수 있다.
FieldNamingPolicy.IDENTITY
{
"justForNamingPolicy": "policy",
"loginForm": {
"id": "rkdxowhd98",
"password": null
},
"profile": {
"name": "강태종"
}
}
FieldNamingPolicy.LOWER_CASE_WITH_DASHES
{
"just-for-naming-policy": "policy",
"login-form": {
"id": "rkdxowhd98",
"password": null
},
"profile": {
"name": "강태종"
}
}
FieldNamingPolicy.LOWER_CASE_WITH_DOTS
{
"just.for.naming.policy": "policy",
"login.form": {
"id": "rkdxowhd98",
"password": null
},
"profile": {
"name": "강태종"
}
}
FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES
{
"just_for_naming_policy": "policy",
"login_form": {
"id": "rkdxowhd98",
"password": null
},
"profile": {
"name": "강태종"
}
}
FieldNamingPolicy.UPPER_CAMEL_CASE
{
"JustForNamingPolicy": "policy",
"LoginForm": {
"id": "rkdxowhd98",
"password": null
},
"Profile": {
"Name": "강태종"
}
}
FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES
{
"Just For Naming Policy": "policy",
"Login Form": {
"id": "rkdxowhd98",
"password": null
},
"Profile": {
"Name": "강태종"
}
}
@SerializedName
직렬화 역직렬화시 사용할 이름을 정할 수 있다.
value : 직렬화시 사용하는 이름
alternate : 역직렬화시 사용하는 이름
예제 코드 (Git)
https://github.com/KangTaeJong98/Example/tree/main/Kotlin/Gson
KangTaeJong98/Example
My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.
github.com
'Kotlin (코틀린)' 카테고리의 다른 글
Kotlin in A..Z - Collections (Filtering Operation) (0) | 2020.12.02 |
---|---|
Kotlin in A..Z - Aggregate Operation (0) | 2020.11.28 |
Kotlin in A..Z - Collection (0) | 2020.11.27 |
Kotlin in A..Z - Coroutine(5) CoroutineScope (0) | 2020.10.27 |
Kotlin in A..Z - Coroutine(4) async (0) | 2020.10.27 |