Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 JSON 배열을 반복 처리하는 방법


이 예제는 안드로이드 앱에서 JSON 배열을 반복 처리(순회)하며 데이터를 추출하는 방법을 단계별로 보여줍니다.

1단계 — 새 프로젝트 만들기

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 후, 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.

2단계 — 레이아웃 XML 작성

다음 코드를 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"
   android:padding="8dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textSize="16sp"
      android:textStyle="bold" />
</RelativeLayout>

3단계 — MainActivity 작성

다음 코드를 src/MainActivity.java에 추가합니다. 이 코드는 문자열 형태의 JSON 데이터를 파싱한 뒤, JSONArray를 for문으로 순회하면서 각 직원의 ID, 이름, 급여 정보를 StringBuilder에 누적하여 화면에 출력합니다.

import androidx.appcompat.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;
   String strJson = "{ \"Employee\" :[{\"ID\":\"01\",\"Name\":\"Sam\",\"Salary\":\"50000\"},"
      + "{\"ID\":\"02\",\"Name\":\"Shankar\",\"Salary\":\"60000\"}] }";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      StringBuilder data = new StringBuilder();
      try {
         JSONObject jsonRootObject = new JSONObject(strJson);
         JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
         for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            int id = Integer.parseInt(jsonObject.optString("ID"));
            String name = jsonObject.optString("Name");
            float salary = Float.parseFloat(jsonObject.optString("Salary"));
            data.append("Employee ").append(i).append(" : \n ID= ")
               .append(id).append(" \n " + "Name= ")
               .append(name).append(" \n Salary= ")
               .append(salary).append(" \n\n ");
         }
         textView.setText(data.toString());
      }
      catch (JSONException e) {
         e.printStackTrace();
      }
   }
}

핵심 로직 살펴보기

optJSONArray("Employee")로 최상위 객체에서 "Employee"라는 이름의 배열을 가져온 후, jsonArray.length()만큼 반복하면서 각 인덱스의 JSONObject를 꺼냅니다. 이후 optString()으로 값을 읽어 원하는 타입(int, float 등)으로 변환하면 됩니다. 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="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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 실행할 모바일 기기를 선택하면, 해당 기기 화면에 아래와 같이 파싱된 직원 정보 목록이 표시됩니다.

안드로이드에서 JSON 배열을 반복 처리하는 방법