Kotlin

[android : kotlin] 코틀린 JSON파싱(JSONObject, JSONArray) 방법 및 예제

코틀린 JSON 파싱 방법

JSONObject 클래스를 사용하여 JSON 문자열과 JSON 배열을 파싱하는 방법에 대해 알아 봅니다.

■첫번째 예제는 JSON 타입의 문자열을 가져오는 방법입니다.

[activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="JSON 파싱 예제"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="left"
        android:text="JSON 타입 데이터:"/>
    <TextView
        android:id="@+id/baseTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="left"
        android:textSize="18sp"
        android:text=""  />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="left"
        android:text="파싱 결과:"/>
    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="left"
        android:text=""
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

</LinearLayout>

[MainActivity.kt]

package edu.kotlin.study

import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONException
import org.json.JSONObject


class MainActivity : AppCompatActivity() {
    private val jsonString =
        "{\"UserInfo\":{\"Name\":\"IU\",\"id\":\"test1\",\"pay\":20000000,\"address\":\"서울시....\"}}"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        baseTextView.text = jsonString
        try {
            val userInfo = JSONObject(jsonString).getJSONObject("UserInfo")
            val userName = userInfo.getString("Name")
            val userId = userInfo.getString("id")
            val userPay = userInfo.getInt("pay")
            val userAddress = userInfo.getString("address")

            resultTextView.text = "이름: $userName\n식별코드: $userId\n" +
                    "연봉: $userPay\n" +
                    "주소: $userAddress"
        } catch (e: JSONException) {
            e.printStackTrace()
        }
 
    }

}

■두번째 예제는 JSON타입의 배열 데이터를 파싱하는 예제입니다. JSONArray를 사용하여 처리합니다.


[activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="JSON 파싱 예제"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="left"
        android:text="JSON 타입 데이터:"/>
    <TextView
        android:id="@+id/baseTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="left"
        android:textSize="18sp"
        android:text=""  />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="left"
        android:text="파싱 결과:"/>
    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="left"
        android:text=""
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

</LinearLayout>

[MainActivity.kt]

package edu.kotlin.study

import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

class MainActivity : AppCompatActivity() {
    private val jsonString =
        "{\"UserInfo\":[{\"Name\":\"IU\",\"id\":\"test1\",\"pay\":20000000,\"address\":\"서울시....\"}" +
                ",{\"Name\":\"홍길동\",\"id\":\"test2\",\"pay\":30000000,\"address\":\"부산시....\"}" +
                ",{\"Name\":\"김영수\",\"id\":\"test3\",\"pay\":40000000,\"address\":\"광주시....\"}]}"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        baseTextView.text = jsonString
        try {


            val userInfo = JSONObject(jsonString)
            val jsonArray = userInfo.optJSONArray("UserInfo")

            var i = 0
            var tempStr = ""
            while (i < jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)

                val userName = jsonObject.getString("Name")
                val userId = jsonObject.getString("id")
                val userPay = jsonObject.getInt("pay")
                val userAddress = jsonObject.getString("address")

                tempStr += "이름: $userName\n식별코드: $userId\n" +
                        "연봉: $userPay\n" +
                        "주소: $userAddress\n"
                i++
            }

            resultTextView.text = tempStr
        } catch (e: JSONException) {
            e.printStackTrace()
        }
	}
}

[build.gradle(Module:app)]

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "edu.kotlin.study"
        minSdkVersion 22
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.1'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

[build.gradle(Project)]

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.3.72"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

[연관 자료]

JSONObject 안드로이드 개발자 가이드 문서

Leave a Reply

error: Content is protected !!