Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidアプリのJSONオブジェクトを解析する方法を徹底解説

この記事では、Kotlinを使用してAndroidアプリでJSONオブジェクトを解析する方法を、サンプルプロジェクトを通してステップごとに詳しく解説します。アセットフォルダに配置したJSONファイルを読み込み、その内容をRecyclerViewで一覧表示するまでの流れを学べます。

ステップ1:Android Studioで新規プロジェクトを作成する

まず、Android Studioを開き、メニューから「File」→「New Project」を選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。プロジェクトのテンプレートには「Empty Activity」を選んでおくとスムーズです。

ステップ2:activity_main.xmlにレイアウトを記述する

次に、res/layout/activity_main.xmlに以下のコードを追加します。ここでは、ユーザー一覧を表示するためのRecyclerViewを配置しています。

<?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">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

ステップ3:アセットフォルダにJSONファイルを作成する

新しいアセットフォルダ(app/src/main/assets)を作成し、その中にuser_list.jsonというファイルを追加します。ファイルには以下のようなユーザー情報を記述します。名前・メールアドレスに加えて、連絡先オブジェクトがネストされた構造になっている点がポイントです。

{
    "users":[
        {
            "name":"Niyaz",
            "email":"testemail1@gmail.com",
            "contact":{
                "mobile":"+91 0000000000"
            }
        },
        {
            "name":"Azhar",
            "email":"testemail2@gmail.com",
            "contact":{
                "mobile":"+91 0000000000"
            }
        },
        {
            "name":"Mahi",
            "email":"testemail3@gmail.com",
            "contact":{
                "mobile":"+91 0000000000"
            }
        }
    ]
}

ステップ4:MainActivity.ktでJSONを解析する

src/MainActivity.ktに以下のコードを追加します。アセットからJSONファイルを読み込み、JSONObjectJSONArrayを使って各ユーザーのデータを取り出し、それぞれリストに格納しています。

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.Charset
class MainActivity : AppCompatActivity() {
    var personName: ArrayList<String> = ArrayList()
    var emailId: ArrayList<String> = ArrayList()
    var mobileNumbers: ArrayList<String> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        val linearLayoutManager = LinearLayoutManager(applicationContext)
        recyclerView.layoutManager = linearLayoutManager
        try {
            val obj = JSONObject(loadJSONFromAsset())
            val userArray = obj.getJSONArray("users")
            for (i in 0 until userArray.length()) {
                val userDetail = userArray.getJSONObject(i)
                personName.add(userDetail.getString("name"))
                emailId.add(userDetail.getString("email"))
                val contact = userDetail.getJSONObject("contact")
                mobileNumbers.add(contact.getString("mobile"))
            }
        }
        catch (e: JSONException) {
            e.printStackTrace()
        }
        val customAdapter = CustomAdapter(this@MainActivity, personName, emailId, mobileNumbers)
        recyclerView.adapter = customAdapter
    }
    private fun loadJSONFromAsset(): String {
        val json: String?
        try {
            val inputStream = assets.open("users_list.json")
            val size = inputStream.available()
            val buffer = ByteArray(size)
            val charset: Charset = Charsets.UTF_8
            inputStream.read(buffer)
            inputStream.close()
            json = String(buffer, charset)
        }
        catch (ex: IOException) {
            ex.printStackTrace()
            return ""
        }
        return json
    }
}

ここで注目すべきは、loadJSONFromAsset()メソッドです。アセットフォルダ内のJSONファイルをストリームで読み込み、UTF-8形式の文字列として返します。その文字列をJSONObjectに変換することで、JSONの解析が可能になります。

ステップ5:CustomAdapterクラスを作成する

新しいクラスCustomAdapter.ktを作成し、以下のコードを追加します。このアダプターは、解析したJSONデータをRecyclerViewの各アイテムにバインドする役割を担います。アイテムをタップすると、そのユーザーの名前をToastで表示する機能も実装しています。

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import java.util.*
class CustomAdapter(
    private var context: Context,
    private var personNames: ArrayList<String>,
    private var emailIds: ArrayList<String>,
    private var mobileNumbers: ArrayList<String>
) :
RecyclerView.Adapter<CustomAdapter.MyViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.rowlayout, parent, false)
        return MyViewHolder(v)
    }
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        // アイテムにデータをセット
        holder.name.text = personNames[position]
        holder.email.text = emailIds[position]
        holder.mobileNo.text = mobileNumbers[position]
        // アイテムクリック時のイベントを実装
        holder.itemView.setOnClickListener { // クリックされたアイテムの人物名をToastで表示
            Toast.makeText(context, personNames[position], Toast.LENGTH_SHORT).show()
        }
    }
    override fun getItemCount(): Int {
        return personNames.size
    }
    inner class MyViewHolder(itemView: View) : ViewHolder(itemView) {
        var name: TextView = itemView.findViewById<View>(R.id.tvName) as TextView
        var email: TextView = itemView.findViewById<View>(R.id.tvEmail) as TextView
        var mobileNo: TextView = itemView.findViewById<View>(R.id.tvMobile) as TextView
    }
}

ステップ6:行レイアウト用のrow.xmlを作成する

新しいレイアウトリソースファイルrow.xmlを作成し、以下のコードを追加します。RecyclerViewの1行分のデザインをCardViewで構成し、名前・メールアドレス・電話番号を表示する3つのTextViewを縦に並べています。

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
    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">
        <!--RecyclerViewの1行分のアイテム-->
        <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@email.com"
            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>
</androidx.cardview.widget.CardView>

ステップ7:AndroidManifest.xmlを確認する

最後に、androidManifest.xmlに以下のコードが記述されていることを確認します。ローカルのJSONファイルを読み込むだけなので、特別なパーミッションの追加は不要です。

<?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」アイコンをクリックします。実行デバイスとして自分のモバイル端末を選択すると、端末の画面にアプリが表示されます。

アプリを起動すると、アセットフォルダのJSONファイルから読み込んだユーザー情報(名前・メールアドレス・電話番号)がRecyclerViewに一覧表示され、各アイテムをタップするとそのユーザーの名前がToastで表示されます。

KotlinでAndroidアプリのJSONオブジェクトを解析する方法を徹底解説

まとめ

このように、KotlinではJSONObjectJSONArrayを使うことで、ネストされたJSONデータも簡単に解析できます。アセットからのファイル読み込み、JSONのパース、RecyclerViewでの表示という一連の流れは、実際のAndroidアプリ開発でも頻繁に登場するパターンなので、ぜひマスターしておきましょう。なお、実務ではGsonやMoshi、kotlinx.serializationといったライブラリを使うと、データクラスへの自動マッピングが可能になり、さらに効率的にJSONを扱えます。

  1. AndroidでJSONを解析する方法を徹底解説!初心者向けステップバイステップガイド

    はじめに この記事では、AndroidアプリでJSONデータを解析(パース)する方法を、実際のコード例とともにわかりやすく解説します。JSONはWeb APIなどで広く利用されているデータ形式であり、Android開発においてその扱い方をマスターすることは非常に重要です。 ステップ1:新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成しましょう。 ステップ2:レイアウトファイルの作成 次に、res/layout/activity_main.xm

  2. AndroidでHTMLを解析する方法!Jsoupを使った実装手順をステップごとに解説

    この記事では、AndroidアプリでHTMLを解析(パース)する方法を、人気のJavaライブラリ「Jsoup」を使ったサンプルコードとともに解説します。Webサイトのタイトルやリンク情報を取得して画面に表示するまでの一連の流れを、初心者にもわかるようにステップごとに紹介します。HTML解析にはJsoupが便利AndroidでHTMLを扱う場合、HTMLパーサーライブラリのJsoupを利用するのが定番です。Jsoupを使えば、URLからHTMLを取得し、CSSセレクタに近い直感的な記法で任意の要素を簡単に抽出できます。スクレイピングやWeb上のデータ取得処理を少ないコード量で実装できるのが大きな