Til. 코틀린 JSON 파싱

Devback·2021년 5월 16일
1

Json은 프론트와 백엔드에서 통신을 할 때 자주 사용하는 형식이다. javascript를 사용할 땐 편하게 파싱했었는데 kotlin으로 파싱할 땐 조금 더 불편한거 같다. 기본이 부족한 내탓이겠지..ㅋㅋ

val jsonString = """
{
	"person" :[
		{
			"id": 0,
			"name": "Mathews Parker",
			"email": "goodsleep@aseep.com"
		},
		{
			"id": 1,
			"name": "json as",
			"email": "123dslfffp@aseep.com"
		},
		{
			"id": 2,
			"name": "json a123",
			"email": "12a23sleep@aseep.com"
		},
	]
}

""".trimIndent()

val jsonObject = JSONObject(jsonString)
val jsonArray = jsonObject.getJSONArray("person")

trimIndent는 스트링 안에 불필요한 띄어쓰기와 첫줄 그리고 끝줄이 빈값이면 지워주는 역할을 한다.

JSONArray는 대괄호를 가지고 JSONObject는 중괄호를 가진다.
JSONObject는 순서가 상관이 없지만 JSONArray는 순서가 중요하다. 아래 코드를 참고하자.

{id : 1, name : "A" } == { name : "A", id : 1}
[1, 'A'] != ['A', 1]
fun test() {
    val jsonString = """
        {
        "person": [
                  {
                    "id": 0,
                    "name": "Mathews Parker",
                    "email": "mathewsparker@franscene.com"
                  },
                  {
                    "id": 1,
                    "name": "Dickson Clements",
                    "email": "dicksonclements@franscene.com"
                  },
                  {
                    "id": 2,
                    "name": "Pat Blair",
                    "email": "patblair@franscene.com"
                  },
                  {
                    "id": 3,
                    "name": "Estela Mckinney",
                    "email": "estelamckinney@franscene.com"
                  },
                  {
                    "id": 4,
                    "name": "Rivera Mcclain",
                    "email": "riveramcclain@franscene.com"
                  }
                ]
        }
    """.trimIndent()

    val jsonObject = JSONObject(jsonString)
    val jsonArray = jsonObject.getJSONArray("person")

    for (i in 0..jsonArray.length() - 1) {
        val iObject = jsonArray.getJSONObject(i)
        val id = iObject.getInt("id")
        val name = iObject.getString("name")
        val email = iObject.getString("email")

        println("================== ${i + 1} 번째==================")
        println("${i + 1}번 id : $id")
        println("${i + 1}번 name : $name")
        println("${i + 1}번 email : $email")
    }
private fun anotherJsonTest() {
        // 레트로핏 통신을 하다보면 자주 보는 패턴인거 같아서 테스트 해봤다.
        val anotherJsonString = """
            {
             "message" : "Jun will be great person"
            }
        """.trimIndent()
			
        println("${anotherJsonString}") // string이라 에러가 나지 않지만 
        println("${anotherJsonString.message}") // 객체의 프로퍼티에 접근 하듯이 접근하면 에러남
        val jsonObject = JSONObject(anotherJsonString)
				val message = jsonObject.getString("message")
        println("${message}")
}

참고

profile
나랑 같이 개발할 사람🖐

0개의 댓글