Android StudioでassetsからJsonファイルを読み込む方法
auです。
Android StudioでJsonファイルを読み込むのに手間取ってしまったのでメモしておきます。
実際のコード
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); try { jsonObj = parseJson(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } private JSONObject parseJson() throws JSONException, IOException { inputStream = this.getAssets().open("Sample.json"); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); JSONObject json = null; String data = ""; String str = bufferedReader.readLine(); while(str != null){ data += str; str = bufferedReader.readLine(); } json = new JSONObject(data); inputStream.close(); bufferedReader.close(); return json; }
openでファイルストリームを取得したあと、BufferedReaderで1行ずつ読み込んでいます。
最後まで読み込むまで続け、最終的にJson型にダンプして完了です。
json型のオブジェクトを返しています。
あとは、ファイルから読み取ったjsonの中身を加工して自由に使うことができます。