アンドロイドでJSONデータを解析する方法は何ですか?
Androidには、JSONデータを解析するためのさまざまな方法が提供されていますが、一般的な方法は2つあります。
- JSONObjectとJSONArrayクラスを使用する。
- 最初に、JSON文字列をJSONObjectオブジェクトに変換します。例えば、String jsonString = “{‘name’:’John’, ‘age’:30, ‘city’:’New York’}”; JSONObject jsonObject = new JSONObject(jsonString);
- その後、キーを使用して対応する値を取得することができます。例:String name = jsonObject.getString(“name”);
int age = jsonObject.getInt(“age”);
String city = jsonObject.getString(“city”); - JSON文字列に配列が含まれている場合は、JSONArrayクラスを使用して解析できます。例えば、String jsonString = “{‘students’: [{‘name’:’John’, ‘age’:20}, {‘name’:’Kate’, ‘age’:22}]}” ;
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray studentsArray = jsonObject.getJSONArray(“students”);
for (int i = 0; i < studentsArray.length(); i++) {
JSONObject studentObject = studentsArray.getJSONObject(i);
String name = studentObject.getString(“name”);
int age = studentObject.getInt(“age”);
// 各学生のデータを処理
} - Gsonライブラリを使用する。
- 最初に、build.gradleファイルにGsonライブラリの依存関係を追加する必要があります:implementation ‘com.google.code.gson:gson:2.8.6’。
- その後、JSON文字列をJavaオブジェクトに変換するためにGsonライブラリを使用することができます。例:String jsonString = “{‘name’:’John’, ‘age’:30, ‘city’:’New York’}”; Gson gson = new Gson(); MyClass obj = gson.fromJson(jsonString, MyClass.class);
- MyClassは、カスタムクラスであり、そのフィールドはJSON文字列のキーと対応する必要があります。例:public class MyClass {
private String name;
private int age;
private String city;// コンストラクタやgetter/setterメソッドは省略
}
実際の状況に応じて適切な方法を選択して、JSONを解析する。