How to parse JSON data in Android?
Android provides various methods for parsing JSON data, here are two common options:
- Use the JSONObject and JSONArray classes.
- First, convert the JSON string to a JSONObject object, for example: String jsonString = “{‘name’:’John’, ‘age’:30, ‘city’:’New York’}”;
JSONObject jsonObject = new JSONObject(jsonString); - Next, you can retrieve the corresponding value using keys like this:
String name = jsonObject.getString(“name”);
int age = jsonObject.getInt(“age”);
String city = jsonObject.getString(“city”); - If the JSON string contains an array, you can use the JSONArray class to parse it. For example:
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"); // Process data for each student } - Using the Gson library:
- First, add the Gson library dependency in the build.gradle file: implementation ‘com.google.code.gson:gson:2.8.6’
-
Next, you can use the Gson library to convert a JSON string into a Java object, for example: String jsonString = “{‘name’:’John’, ‘age’:30, ‘city’:’New York’}”;
Gson gson = new Gson();
MyClass obj = gson.fromJson(jsonString, MyClass.class); - MyClass is a custom class where its fields need to correspond to the keys in a JSON string. For example: public class MyClass {
private String name;
private int age;
private String city;// Constructor and getter/setter methods are omitted
}
The above are two common ways to parse JSON, choose the suitable method for parsing according to the actual situation.