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

KotlinでAndroidアプリのJSONを解析する方法|JSONObjectの使い方を徹底解説

この記事では、Kotlinを使ったAndroidアプリ開発において、JSONObjectクラスを利用してJSONデータを解析する方法を、サンプルコードとともにわかりやすく解説します。

手順1:新規プロジェクトの作成

まず、Android Studioを開き、「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

手順2:レイアウトファイル(activity_main.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"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@android:color/background_dark"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

手順3:MainActivity.kt の編集

src/MainActivity.kt に以下のコードを追加します。このコードでは、文字列として定義したJSONから「Employee」オブジェクトを取得し、従業員の名前と給与を取り出してTextViewに表示しています。JSONの形式が不正な場合に備えて、try-catchによる例外処理も行っています。

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONException
import org.json.JSONObject

class MainActivity : AppCompatActivity() {
    private val jsonString = "{\"Employee\":{\"Name\":\"Niyaz\",\"Salary\":56000}}"
    lateinit var textView: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        textView = findViewById(R.id.textView)
        try {
            val emp = JSONObject(jsonString).getJSONObject("Employee")
            val empName = emp.getString("Name")
            val empSalary = emp.getInt("Salary")
            val string =
                "Employee Name: $empName\\nEmployee Salary: $empSalary"
            textView.text = string
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }
}

手順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.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」アイコンをクリックしてください。表示された候補から接続済みのモバイル端末を選択すると、端末の画面に解析結果が表示されます。

KotlinでAndroidアプリのJSONを解析する方法|JSONObjectの使い方を徹底解説

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

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

  2. 【Android開発】Volleyライブラリを使ってJSONを解析する方法をステップ解説

    Volleyライブラリとは この記事では、AndroidアプリでVolleyライブラリを使用してJSONデータを解析(パース)する方法を、ステップごとにわかりやすく解説します。VolleyはGoogleが提供するHTTP通信ライブラリで、ネットワークリクエストの管理やJSONの取得・解析を少ないコード量で実現できるのが特徴です。 ステップ1:新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを生成してください。 ステップ2:レイアウトファイル(act