How to parse JSON data in Android?

Android provides various methods for parsing JSON data, here are two common options:

  1. Use the JSONObject and JSONArray classes.
  2. 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);
  3. 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”);
  4. 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 }
  5. Using the Gson library:
  6. First, add the Gson library dependency in the build.gradle file: implementation ‘com.google.code.gson:gson:2.8.6’
  7. 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);
  8. 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.

bannerAds