AndroidアプリでJSON値をオブジェクトに保存する方法を徹底解説
この記事では、Androidアプリで取得したJSONデータを解析し、その値を自前で定義したオブジェクト(クラス)に保存する方法を、サンプルコードを交えて解説します。Volleyライブラリでネットワーク経由のJSONを取得し、org.jsonのクラスでパースして、カスタムクラスのインスタンスへ値を格納する一連の流れをステップごとに見ていきましょう。
手順1:Android Studioで新規プロジェクトを作成する
まずはAndroid Studioを起動し、「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトを完成させてください。
手順2:res/layout/activity_main.xml を編集する
次に、レイアウトファイル 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>
上記のコードでは、画面中央にTextViewを1つ配置しています。このTextViewは、後ほどオブジェクトに保存した「name(ユーザー名)」の値を画面に表示するために使用します。
手順3:src/MainActivity.java を実装する
続いて、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とJSONArrayで「users」配列を解析し、各要素から「name」の値を取り出します。取得した値は、内部クラスとして定義したUserInfoオブジェクトに保存され、その内容がTextViewに表示されます。通信エラーが発生した場合には、ErrorListener側でログに出力する仕組みになっています。
手順4:AndroidManifest.xml に権限を追加する
ネットワーク通信を行うため、AndroidManifest.xml に以下のコードを追加します。uses-permissionタグでINTERNET権限を宣言している点が重要です。これを忘れると、通信時にエラーが発生します。
<?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>
手順5:build.gradle に依存関係を追加する
最後に、appレベルの build.gradle に以下のコードを追加します。Volleyライブラリ(com.android.volley:volley)の依存関係を必ず含めてください。
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'
}
アプリを実行して動作を確認する
それでは、アプリを実際に実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続していることを前提に説明します。Android Studioでプロジェクト内の任意のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。デバイス選択ダイアログが表示されたら、お使いのモバイル端末を選択します。しばらくすると、端末の画面にJSONから取り出したユーザー名が以下のように表示されます。

-
AndroidでJSON配列を反復処理する方法をステップごとに解説
この記事では、Androidアプリ開発においてJSON配列(JSONArray)を反復処理する方法を、実際のサンプルコードとともにステップ形式で解説します。org.jsonパッケージのJSONObjectとJSONArrayクラスを使用して、JSON文字列からデータを取り出し、画面に表示するまでの一連の流れを学べます。完成イメージ本チュートリアルでは、従業員情報(ID・名前・給与)を含むJSON文字列を解析し、各要素を順番に読み取ってTextViewに表示するシンプルなアプリを作成します。手順1:Android Studioで新規プロジェクトを作成するまず、Android Studioを起動し
-
【Android】SharedPreferencesで値を保存・読み取り・編集する方法を徹底解説
SharedPreferencesとは? SharedPreferencesは、Androidアプリでキーと値(Key-Value)のペア形式の小さなデータを永続的に保存するための仕組みです。ユーザー名やメールアドレスなどの設定情報、ログイン状態、前回起動時の状態など、SQLiteデータベースを用意するまでもない軽量なデータの保存に最適で、多くのアプリで広く利用されています。 本記事では、実際に動作するサンプルコードをもとに、SharedPreferencesで値を「保存」「読み取り」「編集(クリア)」する方法をステップごとに解説します。 ステップ1:新規プロジェクトを作成する Android