개요
이 예제는 Android 앱에서 JSONArray를 구문 분석(파싱)하는 방법을 단계별로 보여줍니다. JSON은 서버와 클라이언트 간 데이터를 주고받을 때 널리 사용되는 경량 데이터 형식으로, Android 개발에서 API 응답을 처리할 때 반드시 알아야 하는 핵심 기술입니다.
JSONArray는 여러 개의 JSONObject를 배열 형태로 담고 있는 구조입니다. 이 튜토리얼에서는 문자열 형태의 JSON 데이터를 JSONObject와 JSONArray 클래스를 활용해 순서대로 읽어 들인 후, 그 결과를 화면에 출력하는 전체 과정을 살펴보겠습니다.
1단계: 새 프로젝트 만들기
Android Studio에서 File ⇒ New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 새 프로젝트를 만듭니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 다음 코드를 추가합니다. 화면 정중앙에 파싱 결과를 표시할 TextView 하나를 배치하는 간단한 구조입니다.
<?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:id="@+id/textView" android:textSize="24sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </RelativeLayout>
3단계: MainActivity 코드 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다. 이 코드가 JSONArray 파싱의 핵심 부분입니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
String strJson = "{ \"Basic info\"
:[{\"Name\":\"Mash\",\"Age\":\"27\"," +
"\"Gender\":\"Male\"},{\"Name\":\"Niyaz\",\"Age\":\"23\"," +
"\"Gender\":\"Male\"}]}";
String data = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONArray jsonArray = jsonRootObject.optJSONArray("Basic info");
int i=0;
while (i < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int age = Integer.parseInt(jsonObject.optString("Age"));
String name = jsonObject.optString("Name");
String gender = jsonObject.optString("Gender");
data += "Node"+i+" : \n Name= "+ name +" \n
Age= "+ age +" \n Gender= "+ gender + " \n ";
i++;
}
textView.setText(data);
} catch (JSONException e) {e.printStackTrace();}
}
}
코드 동작 원리
- JSON 문자열 준비:
strJson변수에 "Basic info"라는 키를 가진 JSON 문자열을 저장합니다. 이 배열 안에는 이름(Name), 나이(Age), 성별(Gender) 정보를 담은 두 개의 객체가 들어 있습니다. - 루트 객체 생성:
new JSONObject(strJson)로 전체 JSON 문자열을 최상위 JSONObject로 변환합니다. - 배열 추출:
optJSONArray("Basic info")메서드를 사용해 해당 키에 해당하는 JSONArray를 가져옵니다. - 반복문으로 데이터 읽기:
while루프를 돌면서 각 인덱스의 JSONObject에서optString()메서드로 Name, Age, Gender 값을 차례대로 읽어 문자열로 조합합니다. - 예외 처리: JSON 파싱 중 오류가 발생할 수 있으므로
try-catch블록으로JSONException을 처리합니다.
4단계: 매니페스트 파일 설정
androidManifest.xml 파일에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample"> <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 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 파싱된 JSON 데이터가 표시됩니다.

이처럼 JSONObject와 JSONArray 클래스만으로도 별도의 외부 라이브러리 없이 JSON 데이터를 손쉽게 파싱할 수 있습니다. 실제 프로젝트에서는 네트워크 통신으로 받아온 JSON 응답을 같은 방식으로 처리하면 되며, 더 복잡한 데이터 구조를 다룰 때는 Gson이나 Moshi 같은 라이브러리를 활용하는 것도 좋은 선택입니다.