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

Android에서 객체에 JSON 값을 저장하는 방법 완벽 가이드

이 예제는 Android 앱에서 JSON 값을 객체에 저장하는 방법을 보여줍니다. Volley 라이브러리를 사용해 네트워크에서 JSON 데이터를 받아온 후, JSONObject와 JSONArray로 파싱하여 커스텀 클래스 객체에 담는 전체 과정을 단계별로 살펴보겠습니다.

1단계 − Android Studio에서 새 프로젝트 생성

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

2단계 − activity_main.xml 코드 추가

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:app="https://schemas.android.com/apk/res-auto"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:gravity="center"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:textSize="30sp"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</LinearLayout>

위 코드에서는 객체에서 가져온 NAME 값을 화면에 표시하기 위해 TextView를 사용했습니다.

3단계 − MainActivity.java 코드 추가

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   RequestQueue queue;
   String URL = "https://www.mocky.io/v2/597c41390f0000d002f4dbd1";
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      queue = Volley.newRequestQueue(this);
      StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
         @Override
         public void onResponse(String response) {
            textView.setText(response.toString());
            try {
               JSONObject object=new JSONObject(response);
               JSONArray array=object.getJSONArray("users");
               for(int i=0;i<array.length();i++) {
                  JSONObject object1=array.getJSONObject(0);
                  String name =object1.getString("name");
                  UserInfo userInfo=new UserInfo(name);
                  textView.setText(userInfo.name);
               }
            } catch (JSONException e) {
               e.printStackTrace();
            }
         }
      }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
            Log.d("error",error.toString());
         }
      });
      queue.add(request);
   }
   private class UserInfo {
      String name;
      public UserInfo(String name) {
         this.name=name;
      }
   }
}

위 코드의 핵심 흐름은 다음과 같습니다. 먼저 Volley의 StringRequest를 사용해 지정된 URL에서 JSON 문자열 응답을 받아옵니다. 그다음 응답을 JSONObject로 변환하고 "users"라는 JSONArray를 추출합니다. 반복문 안에서 각 항목의 "name" 값을 꺼내 UserInfo라는 내부 클래스(커스텀 객체)에 저장한 뒤, 그 값을 TextView에 표시합니다. 네트워크 오류가 발생하면 ErrorListener가 Logcat에 에러 메시지를 출력합니다.

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.myapplication">
   <uses-permission android:name="android.permission.INTERNET" />
   <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" />
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

서버에서 데이터를 가져오는 앱이므로 매니페스트에 INTERNET 권한이 반드시 선언되어 있어야 합니다. 이 권한이 없으면 네트워크 요청 시 보안 예외가 발생합니다.

5단계 − build.gradle 의존성 추가

build.gradle 파일에 아래 코드를 추가합니다.

apply plugin: 'com.android.application'
android {
   compileSdkVersion 28
   defaultConfig {
      applicationId "com.example.myapplication"
      minSdkVersion 15
      targetSdkVersion 28
      versionCode 1
      versionName "1.0"
      testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
      }
   }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.volley:volley:1.1.0'
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

여기서 가장 중요한 것은 com.android.volley:volley 의존성입니다. 이 라이브러리가 HTTP 통신, 요청 큐 관리, 응답 처리를 담당합니다. 의존성을 추가한 후에는 반드시 Gradle Sync를 실행해야 합니다.

애플리케이션 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바에서 실행(Run) 아이콘을 클릭하세요. 기기 선택 목록에서 자신의 모바일 기기를 고르면, 앱이 실행되면서 아래와 같이 JSON에서 파싱한 이름 값이 화면에 표시됩니다.

Android에서 객체에 JSON 값을 저장하는 방법 완벽 가이드