이 예는 Android에서 JSON 개체를 구문 분석하는 방법을 보여줍니다.
1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.
2단계 − Gradle 스크립트 ⇒ build.gradle에 다음 종속성을 추가하고 동기화하십시오.
apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.sample" minSdkVersion 21 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.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' implementation "com.android.support:recyclerview-v7:23.0.1" // dependency file for RecyclerView implementation 'com.android.support:cardview-v7:23.0.1' // dependency file for CardView }
3단계 − res/layout/activity_main.xml에 다음 종속성을 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:layout_height="match_parent" tools:context=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
4단계 − res/layout/rowlayout _main.xml
에 다음 종속성을 추가합니다.<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android" xmlns:card_view="https://schemas.android.com/apk/res-auto" android:id="@+id/cardView" android:layout_width="match_parent" android:layout_margin="5dp" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp"> <!--items for a single row of RecyclerView--> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textColor="#000" android:textSize="20sp" /> <TextView android:id="@+id/tvEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="[email protected]" android:textColor="#000" android:textSize="15sp" /> <TextView android:id="@+id/tvMobile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="e9999999999" android:textColor="#000" android:textSize="15sp" /> </LinearLayout> </android.support.v7.widget.CardView>
5단계 − src/MainActivity.java에 다음 종속성을 추가합니다.
package com.example.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; public class MainActivity extends AppCompatActivity { // ArrayList for person names, email Id's and mobile numbers ArrayList<String> personNames=new ArrayList<>(); ArrayList<String> emailIds=new ArrayList<>(); ArrayList<String> mobileNumbers=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get the reference of RecyclerView RecyclerView recyclerView=(RecyclerView) findViewById(R.id.recyclerView); // set a LinearLayoutManager with default vertical orientation LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(linearLayoutManager); try { // get JSONObject from JSON file JSONObject obj=new JSONObject(loadJSONFromAsset()); // fetch JSONArray named users JSONArray userArray=obj.getJSONArray("users"); // implement for loop for getting users list data for (int i = 0; i < userArray.length(); i++) { // create a JSONObject for fetching single user data JSONObject userDetail=userArray.getJSONObject(i); // fetch email and name and store it in arraylist personNames.add(userDetail.getString("name")); emailIds.add(userDetail.getString("email")); // create a object for getting contact data from JSONObject JSONObject contact=userDetail.getJSONObject("contact"); // fetch mobile number and store it in arraylist mobileNumbers.add(contact.getString("mobile")); } } catch (JSONException e) { e.printStackTrace(); } // call the constructor of CustomAdapter to send the reference and data to Adapter CustomAdapter customAdapter=new CustomAdapter(MainActivity.this, personNames, emailIds, mobileNumbers); recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView } public String loadJSONFromAsset() { String json=null; try { InputStream is=getAssets().open("users_list.json"); int size=is.available(); byte[] buffer=new byte[size]; is.read(buffer); is.close(); json=new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } }
6단계 − src/CustomAdapter.java
에 다음 종속성을 추가합니다.package com.example.sample; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> { ArrayList<String> personNames; ArrayList<String> emailIds; ArrayList<String> mobileNumbers; Context context; public CustomAdapter(Context context, ArrayList<String> personNames, ArrayList<String> emailIds, ArrayList<String> mobileNumbers) { this.context=context; this.personNames=personNames; this.emailIds=emailIds; this.mobileNumbers=mobileNumbers; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // infalte the item Layout View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false); MyViewHolder vh=new MyViewHolder(v); // pass the view to View Holder return vh; } @Override public void onBindViewHolder(MyViewHolder holder, final int position) { // set the data in items holder.name.setText(personNames.get(position)); holder.email.setText(emailIds.get(position)); holder.mobileNo.setText(mobileNumbers.get(position)); // implement setOnClickListener event on item view. holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // display a toast with person name on item click Toast.makeText(context, personNames.get(position), Toast.LENGTH_SHORT).show(); } }); } @Override public int getItemCount() { return personNames.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView name, email, mobileNo; // init the item view's public MyViewHolder(View itemView) { super(itemView); // get the reference of item view's name=(TextView) itemView.findViewById(R.id.tvName); email=(TextView) itemView.findViewById(R.id.tvEmail); mobileNo=(TextView) itemView.findViewById(R.id.tvMobile); } } }
7단계 − app/manifests/AndroidManifest.xml에 다음 코드 추가
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.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 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 -