이 글에서는 Kotlin을 사용하여 Android 앱에서 JSONObject로 JSON 데이터를 파싱하는 방법을 단계별로 알아봅니다.
1단계: 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 새 프로젝트를 만들기 위해 필요한 모든 정보를 입력합니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>3단계: MainActivity.kt 작성
src/MainActivity.kt에 아래 코드를 추가합니다. 이 예제에서는 문자열 형태의 JSON에서 직원(Employee) 정보인 이름(Name)과 급여(Salary)를 추출하여 화면에 표시합니다.
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONException
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
private val jsonString = "{\"Employee\":{\"Name\":\"Niyaz\",\"Salary\":56000}}"
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
try {
val emp = JSONObject(jsonString).getJSONObject("Employee")
val empName = emp.getString("Name")
val empSalary = emp.getInt("Salary")
val string =
"Employee Name: $empName\nEmployee Salary: $empSalary"
textView.text = string
} catch (e: JSONException) {
e.printStackTrace()
}
}
}코드 설명
JSONObject(jsonString)는 JSON 문자열을 객체로 변환하며, getJSONObject("Employee")로 중첩된 Employee 객체에 접근한 뒤 getString()과 getInt()를 사용해 각각의 값을 읽어옵니다. JSON 파싱 중 발생할 수 있는 오류에 대비해 try-catch 블록으로 JSONException을 처리하는 것이 좋습니다.
4단계: AndroidManifest.xml 확인
androidManifest.xml에 아래 코드가 포함되어 있는지 확인합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 다음과 같이 직원 이름과 급여 정보가 표시됩니다.