ANDROID JSON EXAMPLE
Android JSON Example: Parsing JSON Data in Android
JSON (JavaScript Object Notation) is a lightweight data format commonly used for exchanging data between servers and mobile apps. In Android, you often work with JSON data when dealing with APIs or when fetching data from a server.
In this article, we will walk through an example of how to handle JSON in Android, from fetching JSON data from an API to parsing it into Java objects. We will use the JSONObject class for parsing, but also show how to use libraries like Gson for a more efficient approach.
Step 1: Adding Internet Permission
To make HTTP requests and fetch data from a server, you need to add the following permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
Step 2: Setting Up JSON Data
Let's assume you have the following JSON data coming from a server or an API. Here's a sample JSON response that you might receive:
{
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com",
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
},
"phone_numbers": [
"123-456-7890",
"987-654-3210"
]
}
You will need to parse this JSON data into a Java object in Android.
Step 3: Create a Java Model Class
Before you start parsing the JSON, it's a good idea to create a Java model class that will hold the data. For this example, we will create a Person class that maps to the structure of the JSON response.
Person.java
public class Person {
private String name;
private int age;
private String email;
private Address address;
private List<String> phoneNumbers;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
class Address {
private String street;
private String city;
private String zip;
// Getters and setters
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
In this example, we created a Person class with nested fields like address (which itself is an object) and phoneNumbers (which is a list).
Step 4: Fetching JSON Data from a URL (Network Request)
For this example, we will use the HttpURLConnection class to fetch JSON data from a URL.
You can execute network requests on a background thread to prevent blocking the UI thread (using AsyncTask or newer methods like ExecutorService or Coroutine in Kotlin).
Here’s how to use HttpURLConnection to fetch the JSON data from a server in the background.
FetchDataTask.java
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class FetchDataTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
// Construct the URL object from the given string
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the InputStream and convert it to a string
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
// Convert the buffer to a string
jsonResponse = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return jsonResponse;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Log the result (JSON response)
Log.d("JSON Response", result);
// Now, parse the JSON data
parseJson(result);
}
private void parseJson(String jsonData) {
try {
// Convert JSON string to a JSONObject
JSONObject jsonObject = new JSONObject(jsonData);
// Extract data from JSON
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String email = jsonObject.getString("email");
// Parse nested JSON object (Address)
JSONObject addressJson = jsonObject.getJSONObject("address");
String street = addressJson.getString("street");
String city = addressJson.getString("city");
String zip = addressJson.getString("zip");
// Parse JSON array (Phone numbers)
JSONArray phoneNumbersJsonArray = jsonObject.getJSONArray("phone_numbers");
List<String> phoneNumbers = new ArrayList<>();
for (int i = 0; i < phoneNumbersJsonArray.length(); i++) {
phoneNumbers.add(phoneNumbersJsonArray.getString(i));
}
// Log the parsed data
Log.d("Parsed Data", "Name: " + name + ", Age: " + age + ", Email: " + email);
Log.d("Address", "Street: " + street + ", City: " + city + ", Zip: " + zip);
Log.d("Phone Numbers", phoneNumbers.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this code:
- AsyncTask is used to fetch data in the background without blocking the UI.
- We use
HttpURLConnectionto make the network request and retrieve the JSON response as a string. - After fetching the data, we call the
parseJson()method, which usesJSONObjectandJSONArrayto parse the JSON data.
Step 5: Calling the AsyncTask
To fetch the JSON data, simply call the FetchDataTask and pass the URL from which to fetch the JSON.
MainActivity.java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call the AsyncTask to fetch JSON data
new FetchDataTask().execute("https://api.example.com/data");
}
}
Step 6: Conclusion
In this tutorial, we demonstrated how to:
- Fetch JSON data from a server using HttpURLConnection.
- Parse the JSON data into a
Personobject using theJSONObjectandJSONArrayclasses. - Work with nested JSON objects and arrays.
This is a basic example of how to handle JSON data in Android. For more advanced use cases, you can explore libraries like Gson or Jackson for easier and more efficient JSON parsing. However, using JSONObject and JSONArray directly is still a great option for handling simple JSON responses.

0 Comments