CodeGym /행동 /Kotlin SELF /Collection gwa Map eul JSON eseo

Collection gwa Map eul JSON eseo

Kotlin SELF
레벨 48, 레슨 0
사용 가능

1. Sogae

Cheoeum-e Json.encodeToString() i “eoneu saienga jache ro” yeppeun JSON eul mandeureo juneun geot-eul bomyeon, munje-ga yeong-wonhi haegyeol-doen geot gat-eun neukkim-i deul su itsseumnida. Hajiman serialization-eun danji “file-e jeojang” man-i anipnida. Geugeos-eun ttohan contract imnida: data format-i eotteohge doelji, dareun program-i geugeos-eul ihaehal su inneunji, han dal dwi-e na jasin-i dasi ilg-eodo ulji an-go ihaehal su inneunji, geurigo nachunge format-eul bakkul ttae eolmana apeulji.

JSON-eun danji “jeojanghaneun string” i anira sotong-ui eoneo imnida. Geurigo JSON-eun jasin-ui gyuchik-i itsseumnida: array [...], object {...}, string, number, true/false geurigoh null eul al-go itsseumnida. Kotlin-eun atsi-dasihae, type-i deo pungbu-hajyo: list, set, map, nullable type, data class deung deong i manhseumnida. Geuraeseo oneul-ui mogpyoneun i geot imnida: Kotlin collection i JSON-eseo eotteohge byeonhwan doelji reul 미리 gamsiha-go, eodi-eseo 함jeong-i saenggineunji reul baewoboneun geot.

Daeeung gwangye: Kotlin collection gwa JSON hyeongtae

Code-reul sseugi jeon-e, meori sog-e “daeeung pyoreul” mandeureo du-myeon yuyonghamnida. Kotlin eseo JSON euro “beonyeok” haneun beonyeokgi gat-eun geot imnida.

Kotlin type Uimi (semantics) JSON-eseo daebubun eotteohge doeneunji
List<T>
sunseo-ga inneun yeollam, jungbok heoyong JSON array [...]
Set<T>
yu-ilhan element, sunseo-neun botong jungyohaji aneum JSON array [...] (geurae, yeogido array)
Map<String, V>
key → value, key-neun munjayeol JSON object { "key": value }
Map<K, V> ( K ga String i anin gyeong-u) key → value, hajiman key-ga “string-i anin” gyeong-u daebubun JSON object but key-ga string-euro byeonhwan-doem (yeogi-eseo nuance-ga sijak)

Map e daehae gibonjeog-euro gieokhaeya hal geot: geugeos-eun key-value pair-ui collection imnida. key-neun yuilha-go, value-neun jungbok doel su itsseumnida. Kotlin-eun Map i pair-reul jeojanghago key-ro jeobgeun-eul jeongonghaneun teukbyeolhan collection type irago tto tteureupnida.

Jigeum-buteo gaksi gyeong-u reul han gae-ssik, jjalbgo swipge ihaehal su inneun yesi-ro salpyeobogetseumnida.

3. List wa Set eul JSON-eseo: array

List<T> in JSON: array [...]

List-neun JSON-e daehae gajang chinjeolhan type imnida. List<String> i itdamyeon, geoui eotteon saram (geurigoh eotteon system) do swipge string array-in JSON-eul ihaehamnida. List-neun element-reul sunseo-daero jeojanghago, index-neun 0-buteo sijakhamyeo, index-ro jeopgeun-i ganeunghamyeo — i geotdeul-eun List contract-ui jungyohan bubun imnida.

Uri-ui gyoyuk mini app (gaseong “BudgetBuddy”, jibul tracker) eseo jibul-ui tag — e.g. food, coffee, taxi — reul jeojanghago sipdago haebopsida. Uimi-sang tag-neun list-ro gajigo itneun geosi pyeonlihan gyeong-u-ga manhseumnida.

Yesi 1: List<String> ga JSON array-ro byeonhwan

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class Tags(val items: List<String>)

fun main() {
    val json = Json { prettyPrint = true }
    println(json.encodeToString(Tags(listOf("kotlin", "json"))))
    // {
    //     "items": [
    //         "kotlin",
    //         "json"
    //     ]
    // }
}

Yeogiseoneun modeun geosi aju yesang ganeunghamnida: list-ga array-ga doeeotseumnida. Geurigo i geos-eun serialization-i “dangyeonhi yesanghan daero” dongjakhanen gyeong-u imnida.

Set<T> in JSON: yeogido array

Set eseo cheoeum gajeojineun jageun cognitive dissonance: Kotlin-eseoneun List 와 Set eul myeonghwahi gu-bunhamnida. Set eun 오직 yu-ilhan element-man jeojanghaneun geos-i go, i geos-i 핵심 아이디어 imnida. Kotlin documentation-eun tto tteureupnida: Set eun yu-ilhan element-reul jeojanghago, ilbanjeog-euro sunseo-neun 보장되지 않으며, null do han beon-man gajil su itsseumnida.

Hajiman JSON-eun “set” 라는 별도의 type-eul gaji-go 있지 않습니다. Geuraeseo serialization-eun botong gajang nollijeogin seontaeg-eul hamnida: Set eul JSON array-ro bakkupnida. Jeuk, hyeongtae man bomyeon JSON-eun List wa ttokgatseumnida.

Geurigo yeogi-seo jungyohan geot: yu-ilseong-eun JSON-ui seongjil-i 아닙니다. Yu-ilseong-eun dangsin-ui yakson (geurigoh Kotlin code logic) imnida.

Yesi 2: Set<String> do array-ga doenda

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class UniqueTags(val items: Set<String>)

fun main() {
    val json = Json { prettyPrint = true }
    println(json.encodeToString(UniqueTags(setOf("food", "coffee"))))
    // {
    //     "items": [
    //         "food",
    //         "coffee"
    //     ]
    // }
}

Gyeolgwa man bomyeon — pyeongbeomhan array imnida. Geuraeseo i JSON-eul “bakkeuro” jeongonghamyeon (yeg: dareun system-e), geudeul-eun i geosi set-inji al su eopsseumnida. Dangsin-i mal로, tteun munseo-ro alryeo jweoya hamnida.

4. Map<String, V> in JSON: object {...}

Jigeum-buteo map (Map) eul salpyeobopseumnida. Map ui uimi-neun “key → value” pair-reul jeojanghaneun geos이며, key-neun yu-ilha-go, key-ro jeopgeunhaneun geosi juyo yeonsan imnida.

JSON object {...} neun bonjiljeog-eurodo “key → value” imnida. Dan, key-neun munjayeol-imnida. Geuraeseo Map<String, V> neun JSON-e yeppeuge matseumnida: map-ui key-ga field name-i doeeo pyeongbeomhan object-ga doemnida.

BudgetBuddy-eseo-neun, yegleul deureo category byeol jibul 총액 eul jeojanghal ttae aju yuyonghamnida: "food" -> 1200, "taxi" -> 450.

Yesi 3: Map<String, Int> ga JSON object-ro byeonhwan

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class Counters(val byName: Map<String, Int>)

fun main() {
    val json = Json { prettyPrint = true }
    val data = Counters(mapOf("apples" to 2, "bananas" to 5))
    println(json.encodeToString(data))
    // {
    //     "byName": {
    //         "apples": 2,
    //         "bananas": 5
    //     }
    // }
}

I geos-eun in-gan-i bogi-e “chingeunghan” hyeongtae-ro, compact-hago nune jal deuleomyeo, ilggi swipseumnida. Geuraeseo Map<String, V> neun JSON-eseo jarju sayongdoemnida.

5. Munjayeol i anin key-reul gajin Map: JSON-eseo eotteohge doeneun-ga

JSON-eseo object key-neun hangsang string imnida. Seupyo-ga susa-cheoreom boyeodo — geugeos-do string-imnida (yeg: "10"). Geuraeseo Map<Int, Int> reul serialize hamyeon, “JSON hyeongtae” ro-neun yejeonhi object {...} iga doego, key-neun string-euro bakkwipnida.

Eotteon ttaeneun muhaehae boyeojiman, eotteon ttaeneun integration-eul mangchindaeumyeo, nuga “numeric key” reul gidaehaetneunde JSON object-eseoneun geureon geot-i wonrae eopsseumnida.

Yesi 4: Map<Int, Int> — key-neun "10", "20" cheoreom string-i doenda

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class IntKeyCounters(val byId: Map<Int, Int>)

fun main() {
    val json = Json { prettyPrint = true }
    val data = IntKeyCounters(mapOf(10 to 3, 20 to 7))
    println(json.encodeToString(data))
    // {
    //     "byId": {
    //         "10": 3,
    //         "20": 7
    //     }
    // }
}

Juyeoui: Kotlin-eseo key-neun 10, 20"10", "20" (string) ro doeeotseumnida.

I geos-eul dasi Kotlin-euro 같은 Map<Int, Int> 로 read back hamyeon, library-ga botong string key-reul Int 로 parse hal su itsseumnida. Hajiman i JSON-i dareun system-euro neomeogass-eul ttae, geugoseo key "010" i "10" gwa dareuge chwi급 doenda-geona, key-ga hangsang number-ga anira-myeon — ije “adventure” ga sijakdoem니다.

6. Eonje Map i format-euroseon 안 joheul ttae

Kotlin-eseo Map eun pyeonlihan gujo imnida. Hajiman code-reul wihan pyeonui wa format-eul wihan pyeonui-neun dareun munje imnida. Kotlin-eun Map i pair-ui 집합이며, pair-ui sunseo-neun uimi-ui ilbu-ga 아니라고 boyeojumnida (dua map-eun pair sunseo-wa sanggwan-eopsi gateum).

Jigeum-buteo jarju naneun munje sanghwang-eul sangsanghaeboseyo:

Key-reul string-i anira bogjaphan object-ro 하고 싶습니다 (yeg: data class CategoryKey(val name: String, val year: Int)). Kotlin-eseoneun 가능하지만, JSON object-eseo-neun geureon key-reul “예쁘게” damgi himdeumnida.

Key-reul Int 로 하고 싶지만, key-e 중요한 format-i itsseumnida. yegleul deureo "00123" cheoreom leading zero-ga uimi-ga inneun “code” ra면. Kotlin-eseoneun munjayeol-lo jeojanghal geot imnida. Hajiman Int 로 jeojanghagiro gyeoljeonghaetdamyeon, serialize 했다가 dasi 되돌릴 ttae "00123" 와 "123" 을 구분할 su eopsseumnida.

Format-eul 확장하고 싶습니다. oneul-eun “key → value” pair-e 한 gajiga 충분하지만, naeil-eun comment, date, author-reul deohago 싶습니다. Map eun resistance-hae jigi sijakhamnida. value-ga bogjap-haejigo, format-i ttaeroneun deo an boyeogil su itsseumnida.

Ireohan gyeong-u-neun, jom deo gillyeodo format-eul deo 명시적으로 mandeuneun geosi joheun gyeong-u-ga manhseumnida.

7. Daech'e: “map-eul record list-ro” List<Entry>

JSON-eul “han 줄-ui yeppeum” boda deo jungyo하게 yeogindamyeon, Map<K, V> dae신 다음-gwa gateun object list format-eul jarju sayonghamnida:

[
  {"key": 10, "value": 3},
  {"key": 20, "value": 7}
]

Gilyeojiman, 장점은 다음-gwa gatseumnida:

  • key-ga JSON object-ui string key-e sum-eo deureoganeun geosi 아니라, value-roseo 숫자-reul yujihamnida;
  • format-eul 확장하기 swipseumnida (field-reul deo hal su itsseumnida);
  • validation gwa documentation-i deo swipseumnida.

Yesi 5: Map<Int, Int> dae신 record list

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class IntCounterEntry(val key: Int, val value: Int)

@Serializable
data class IntCounterList(val items: List<IntCounterEntry>)

fun main() {
    val json = Json { prettyPrint = true }
    val data = IntCounterList(listOf(IntCounterEntry(10, 3), IntCounterEntry(20, 7)))
    println(json.encodeToString(data))
}

JSON-eun dae략 ireohge boyeol geos imnida (논리-ga jungyo, indent-eun ttajiji anseumnida):

{
  "items": [
    { "key": 10, "value": 3 },
    { "key": 20, "value": 7 }
  ]
}

Ne, text-ga neul-eonaseumnida. Hajiman format-i “말해 줍니다”: yeogi-seo key neun 숫자, value

8. Yesi: jibul report-reul collection + Map 으로

Yesi-deul-i heobe imyeon an doeni, uri-ui gaseong BudgetBuddy-wa yeongyeolhaebopseumnida. jibul list-ga 있고, report-reul mandeulgo sipseumnida: category byeol 총합.

Jibul list-neun List<Expense> imnida. 최종 report-neun Map<String, Int> (category → sum) ro jeojanghamyeon pyeonlihamnida. I gyeong-u Map eun uimi-sang jeongmal jal matseumnida: category-ga string-igo, JSON object-ga jayeonseureopge doemnida.

Yesi 6: “expenses + category byeol sum” model

import kotlinx.serialization.Serializable

@Serializable
data class Expense(val title: String, val category: String, val amount: Int)

@Serializable
data class Report(val expenses: List<Expense>, val totalByCategory: Map<String, Int>)

Yeogiseo uri-ga uidojeog-euro seontaeghan geot:

  • expenses: List<Expense> — record-ui yeonsok (file-e jayeonseureoum).
  • totalByCategory: Map<String, Int> — 요약, key-ga string-ira JSON object-ga 올바르고 ilggi swipseumnida.

9. List-eseo Map eul “magic eopsi” mandeuneun bangbeob

Report-reul malhaet으니, geubi hangsang saenggineun sil무jeok jilmum: “Geureom Map<String, Int> reul expenses list-eseo eotteohge mandeureo?”

Loop-reul dolmyeo sum-eul 직접 누적할 수도 있습니다. Hajiman Kotlin collection-eun 변환 도구가 manhseumnida. yegleul deureo map-eul wihan pyeonrihan operation mapKeys(), mapValues() ga itsseumnida — key나 value-reul 변환하고 싶을 때 sayonghamnida.

Oneul-eun gajang dan순하고 읽기 쉬운 버전 — pyeongbeomhan for — 으로 haebopseumnida (초보ja-deul-i ilgi swipseumnida). da-eum-eun deo func-style ro jarju ssege doel geos imnida.

Yesi 7: MutableMap e sum 누적

fun buildTotals(expenses: List<Expense>): Map<String, Int> {
    val totals = mutableMapOf<String, Int>()

    for (e in expenses) {
        val old = totals[e.category] ?: 0
        totals[e.category] = old + e.amount
    }

    return totals
}

Style-eul jom bogoseyo: totals[e.category] ?: 0 — “아직 값이 없으면 0으로 본다” 라는 jeontongjeog pattern imnida.

10. List<Entry> 와 Map gyeonhwan

Ttaeroneun format-euro “record list” ga yuri-hajiman, code-eseoneun Map cheoreom sayonghago sipseumnida. Geureom yeongyeolhaeseo bidirectional 변환이 필요합니다.

Kotlin-eun collection-eseo Map eul mandeuneun yeoreo bangbeob-eul 제공hamnida. 그중 하나가 associate() imnida: 각 element마다 Pair(key, value) reul 반환하면 Kotlin-i geugeos-euro map-eul 구성hamnida. Documentation-eun associate() reul seolmyeonghamyeo, Pair 로부터 Map eul 만든다고 강조합니다.

Yesi 8: record list → Map

fun asMap(items: List<IntCounterEntry>): Map<Int, Int> {
    return items.associate { it.key to it.value }
}

Yesi 9: Map → record list

fun asList(map: Map<Int, Int>): List<IntCounterEntry> {
    return map.map { (k, v) -> IntCounterEntry(k, v) }
}

Yeogi-seo jungyohan geot: Map eun dan순히 “pair list” ga 아닙니다. key 유일성과 key 접근이라는 고유한 성질이 있습니다. Geuraeseo dangsin-eun “code pyeonui” wa “format 명확성/호환성” 중 mueos-i 더 중요한지-e 따라 구조를 seontaegham니다.

11. Eotteohge seontaehal-kka: Map inji List<Entry> inji

JSON-eul seolgyehal ttae, jageun 선택 규칙-eul 가지고 있-eumyeon pyeonlihamnida. 절대진리라기보다 상식에 대한 가이드 imnida.

flowchart TD
    A["Need to preserve mapping key → value"] --> B{Are keys strings?}
    B -- "Yes" --> C["OK: Map⟨String, V⟩ → JSON object"]
    B -- "No" --> D{Are keys definitely numbers and everyone is OK with that?}
    D -- "Yes" --> E["Map⟨Int, V⟩ is possible, but keys become strings"]
    D -- "No / not sure" --> F["Better: List⟨Entry⟩ with key/value fields"]

Geurigo ne: ttaeroneun jeong답-i “잘 모르겠는데…” imnida. Programming-eseoneun i geos-do hyeonmyeonghan 입장일 su itsseumnida, teukhi cheot integration jeon-eun.

12. Jarju naneun silsu

Silsu 1: Set i JSON-eseo “set” 으로 유지될 georago gidae하기.
Kotlin-eseo Set irinikka JSON-eseo-do “teukbyeolhan mueonga” ga it-eul georago saenggak하기 쉽습니다. Hajiman JSON-eun dan순han format-imnida: “set” type-i eops-eunikka Set eun List cheoreom array-ga doemnida. element yu-ilseong-eun dangsin-ui logic이지, format-ui seongjil-i 아닙니다. Jungyohamyeon, data-eul chuga할 ttae-do 읽을 ttae-do yu-ilseong-eul 명시적으로 보장해야 합니다.

Silsu 2: Map<Int, ...> reul sseugo JSON-eseo key-ga string-i 된다는 geot-eul 잊기.
Munje-neun serialization-i “나쁘다” ga 아닙니다 — JSON object key-ga string-in 이상, geugeos-eun 유일하게 가능한 동작입니다. Munje-neun 기대치입니다: oneul JSON-eul bomyeon "10": 3 cheoreom boyeojiman, naeil-eun dareun saram (ttoneun 미래-ui na) i geot-eul string key 로 인식하게 되고, leading zero, 공백, teukbyeolhan format 등이 가능해집니다. Key-ga uimi-sang “susa” go format-i 중요한 경우라면, record list 로 바꾸는 게 더 쉬운 gyeong-u-ga manhseumnida.

Silsu 3: “복잡한 key” reul gajin Map eul mandeulgo “예쁜 JSON” eul 기대하기.
Kotlin-eseo map key-neun geoui mueos-ina doel su 있지만, JSON object-neun geureohge mot 합니다: key-neun string 이어야 합니다. Geuraeseo object key-neun daebubun 불편하거나 예상 밖 format-euro 이어집니다. I gyeong-u-neun 명시적 model-i joheumnida: List<Entry> 로 하고, key-reul 독립 field 로 둡니다. key-ga 복잡한 object 여도 괜찮습니다 (JSON-eseo value는 object가 될 수 있지만, key는 안 됨).

Silsu 4: “더 예뻐 보여서” 구조를 고르고, 되돌려 읽을 수 있는지-e 대한 기준을 무시하기.
초보ja-ga jarju 빠지는 함정입니다: “Map 이 compact 하네, 그럼 이걸로.” 그런데 나중에 decode 하려고 보면 조건이 너무 많아집니다: 어떤 key가 허용되는지, 숫자로 파싱해도 되는지, 빈 string 은 어떻게 할지 등. Joheun 기준은 i jilmum imnida: “반년 뒤에 힌트 없이 decode 를 직접 작성해도 실수 없이 할 수 있을까?” 조금이라도 애매하면, format-eul 더 명시적으로 하세요.

Silsu 5: “저장 format-e pyeonhan 것” 과 “code-eseo pyeonhan 것” 을 한 덩어리로 섞기.
Code-eseoneun Map 이 pyeonlithamnida (key 접근이 빠름). File/format-eseoneun List ga pyeonlithamnida (명시적 sunseo, 확장성, typed field). I geot-eun jeong-sang imnida — “file로 내보내기” 와 “file에서 가져오기” 를 별도의 step으로 두세요. Kotlin collection-ui 장점은 List 와 Map 사이를 대개 associate() 와 map { ... } 으로 두 줄 안에 변환할 수 있다는 점입니다.

1
과제
Kotlin SELF, 레벨 48, 레슨 0
잠금
노트 태그
노트 태그
1
과제
Kotlin SELF, 레벨 48, 레슨 0
잠금
고유 태그
고유 태그
1
과제
Kotlin SELF, 레벨 48, 레슨 0
잠금
지출 보고서
지출 보고서
1
과제
Kotlin SELF, 레벨 48, 레슨 0
잠금
id별 카운터
id별 카운터
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION