0% found this document useful (0 votes)
1 views7 pages

Android Quiz 3

The document provides an overview of JSON (JavaScript Object Notation), detailing its syntax, basic data types, and key rules for usage. It also outlines various use cases for JSON, including web development, configuration files, and data serialization, along with a practical example of reading JSON data in an Android application. The document includes code snippets demonstrating how to load and parse JSON data from a file in a mobile app context.

Uploaded by

Ahmad Tahir322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views7 pages

Android Quiz 3

The document provides an overview of JSON (JavaScript Object Notation), detailing its syntax, basic data types, and key rules for usage. It also outlines various use cases for JSON, including web development, configuration files, and data serialization, along with a practical example of reading JSON data in an Android application. The document includes code snippets demonstrating how to load and parse JSON data from a file in a mobile app context.

Uploaded by

Ahmad Tahir322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Name: -

M Ahmad Tahir
Department: -
Computer Science
Subject: -
Mobile Application Development
Semester: -
8th
Roll No: -
FC-072
Submitted to: -
Ms. Samra Tariq
Work: -
Quiz 3
What is a JSON file?
JSON, which stands for JavaScript Object Notation, is a lightweight, text-based, open
standard format designed for human-readable data interchange. It was derived from
JavaScript but is a language-independent format, meaning it can be used with many
different programming languages. JSON is commonly used for transmitting data
between a server and a web application (e.g., sending data from the server to be
displayed on a webpage, or vice versa).

Explain syntax and use?


Syntax

JSON syntax is built on two fundamental structures:

1. Objects:
o An unordered collection of key/value pairs.
o Begins with a left curly brace { and ends with a right curly brace }.
o Each key is a string enclosed in double quotes (").
o Each key is followed by a colon :.
o Values can be strings, numbers, booleans (true or false), arrays, other
JSON objects, or the null value.
o Key/value pairs are separated by commas ,.
o Keys within an object should ideally be unique.
o The order of key/value pairs in an object is not significant.
2. Arrays:
o An ordered list of values.
o Begins with a left square bracket [ and ends with a right square
bracket ].
o Values are separated by commas ,.
o Array elements can be of any valid JSON data type (strings, numbers,
booleans, objects, other arrays, or null).

Basic Data Types in JSON:

 String: A sequence of zero or more Unicode characters, enclosed in double


quotes ("). Special characters must be escaped with a backslash (\).
 Number: A signed decimal number. It can be an integer or a floating-point
number. Octal and hexadecimal formats are not used. It cannot include non-
numbers like NaN or Infinity.
 Boolean: Can be either true or false.
 Array: An ordered list of values.
 Object: An unordered collection of key/value pairs.
 null: Represents an empty value or absence of data.
Key Syntax Rules and Restrictions:

 Keys must be strings enclosed in double quotes.


 String values must be enclosed in double quotes (single quotes are not
allowed).
 No trailing commas are allowed in objects or arrays (e.g., {"key": "value",} is
invalid).
 Comments are not allowed in JSON.
 Whitespace (spaces, tabs, newlines) between elements is generally ignored
but can make the JSON more human-readable.
 JSON files typically use the .json extension and the MIME type
application/json.
 JSON exchange in an open ecosystem should be encoded in UTF-8.

Use Cases

JSON is widely used in various applications due to its simplicity and ease of parsing:

1. Web Development (APIs): It's the most common format for data exchange
between web clients (browsers) and servers. RESTful APIs frequently use JSON
to send and receive data.
2. Configuration Files: Many applications use JSON to store configuration
settings because it's easy for both humans and machines to read and write.
3. Data Storage: While not a database itself, JSON is often used to structure data
that is then stored in NoSQL databases like MongoDB, which use JSON-like
document formats (BSON).
4. Data Serialization: Converting data structures or objects in a programming
language into a format that can be stored or transmitted, and then
reconstructed later.
5. Logging: Storing log data in JSON format makes it easier to parse, search, and
analyze.
6. Inter-Process Communication: Exchanging data between different software
applications or components.

How you can read data from a JSON file explain with the help of
code.
How to Read Data from a JSON File

Reading data from a JSON file typically involves opening the file, reading its content as a
string, and then parsing that string into a data structure native to the programming language
being used
MainActivity.java
package com.example.json;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";


private TextView jsonDataTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize the TextView from the layout


jsonDataTextView = findViewById(R.id.json_data_textview);

// Load and parse the JSON data


loadJSONFromAsset();
}

private void loadJSONFromAsset() {


String jsonString;
try {
// Open the JSON file from the assets folder
InputStream inputStream = getAssets().open("sample.json"); //
Ensure your file is named sample.json
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();

// Convert the byte array to a String


jsonString = new String(buffer, StandardCharsets.UTF_8);

// Parse the JSON string


parseJson(jsonString);

} catch (IOException ex) {


Log.e(TAG, "IOException: Error reading JSON file from assets",
ex);
jsonDataTextView.setText("Error reading JSON file: " +
ex.getMessage());
return; // Exit if file reading fails
} catch (JSONException ex) {
Log.e(TAG, "JSONException: Error parsing JSON data", ex);
jsonDataTextView.setText("Error parsing JSON data: " +
ex.getMessage());
}
}
private void parseJson(String jsonString) throws JSONException {
// Create a JSONObject from the JSON String
JSONObject rootObject = new JSONObject(jsonString);

// Extract data from the root object


String studentName = rootObject.getString("studentName");
int studentAge = rootObject.getInt("age");
boolean isEnrolled = rootObject.getBoolean("isEnrolled");

// Log some basic info


Log.i(TAG, "Student Name: " + studentName);
Log.i(TAG, "Student Age: " + studentAge);
Log.i(TAG, "Is Enrolled: " + isEnrolled);

// Example: Displaying some data in the TextView


StringBuilder displayText = new StringBuilder();
displayText.append("Student Name: ").append(studentName).append("\
n");
displayText.append("Age: ").append(studentAge).append("\n");
displayText.append("Enrolled: ").append(isEnrolled).append("\n\n");

// Accessing a nested JSONObject ("contact")


JSONObject contactObject = rootObject.getJSONObject("contact");
String email = contactObject.getString("email");
String phone = contactObject.getString("phone");
displayText.append("Contact:\n");
displayText.append(" Email: ").append(email).append("\n");
displayText.append(" Phone: ").append(phone).append("\n\n");
Log.i(TAG, "Email: " + email);

// Accessing a JSONArray ("courses")


JSONArray coursesArray = rootObject.getJSONArray("courses");
displayText.append("Courses:\n");
Log.i(TAG, "Courses:");
for (int i = 0; i < coursesArray.length(); i++) {
JSONObject courseObject = coursesArray.getJSONObject(i);
String courseName = courseObject.getString("courseName");
int credits = courseObject.getInt("credits");

displayText.append(" - ").append(courseName).append("
(").append(credits).append(" credits)\n");
Log.i(TAG, " - Course: " + courseName + ", Credits: " +
credits);
}

// Set the formatted text to the TextView


jsonDataTextView.setText(displayText.toString());
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/json_data_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading JSON data..."
android:textSize="16sp" />

</LinearLayout>

Sample.json
{
"studentName": "Wahab Noman",
"studentID": "FC076",
"age": 21,
"isEnrolled": true,
"courses": [
{
"courseName": "Android Development",
"credits": 4
},
{
"courseName": "Economics In Computing",
"credits": 2
},
{
"courseName": "Parallel & Distributive Computing",
"credits": 2
}
],
"contact": {
"email": "[email protected]",
"phone": "0000000000"
}
}

Output

You might also like