org.json लाइब्रेरी का उपयोग करके JSON एरे पार्स करना और इटरेट करना
एंड्रॉइड में बिल्ट-इन org.json पैकेज (JSONArray, JSONObject) का उपयोग करके JSON डेटा पार्स किया जा सकता है। यह उदाहरण एक JSON स्ट्रिंग से एरे निकालकर उसे लूप के माध्यम से प्रोसेस करना दिखाता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में प्रोजेक्ट बनाएं। कोई अतिरिक्त निर्भरता नहीं चाहिए - org.json SDK में शामिल है।
चरण 2: लेआउट फ़ाइल
res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvJsonResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:lineSpacingExtra="4dp"
tools:text="JSON पार्स परिणाम यहाँ दिखेगा" />
</ScrollView>
</RelativeLayout>
चरण 3: MainActivity में JSON पार्सिंग लॉजिक
package com.app.sample;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView tvJsonResult;
// नमूना JSON स्ट्रिंग (सामान्यतः API से प्राप्त होती है)
private static final String JSON_STRING = "{\n" +
" \"employees\": [\n" +
" {\"id\": \"01\", \"name\": \"राहुल\", \"salary\": \"50000\", \"department\": \"IT\"},\n" +
" {\"id\": \"02\", \"name\": \"प्रिया\", \"salary\": \"60000\", \"department\": \"HR\"},\n" +
" {\"id\": \"03\", \"name\": \"अमित\", \"salary\": \"55000\", \"department\": \"Finance\"},\n" +
" {\"id\": \"04\", \"name\": \"स्नेहा\", \"salary\": \"65000\", \"department\": \"IT\"}\n" +
" ]\n" +
"}";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvJsonResult = findViewById(R.id.tvJsonResult);
parseAndDisplayJson();
}
private void parseAndDisplayJson() {
StringBuilder output = new StringBuilder();
try {
// रूट JSONObject बनाएं
JSONObject jsonRoot = new JSONObject(JSON_STRING);
// "employees" एरे प्राप्त करें
JSONArray jsonArray = jsonRoot.getJSONArray("employees");
output.append("कुल कर्मचारी: ").append(jsonArray.length()).append("\n\n");
// एरे पर इटरेट करें
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
// सुरक्षित तरीके से मान निकालें
String id = employee.optString("id", "N/A");
String name = employee.optString("name", "अज्ञात");
String salaryStr = employee.optString("salary", "0");
String department = employee.optString("department", "N/A");
// संख्यात्मक मान के लिए पार्सिंग
double salary = 0;
try {
salary = Double.parseDouble(salaryStr);
} catch (NumberFormatException e) {
salary = 0;
}
// फॉर्मेटेड आउटपुट
output.append("कर्मचारी ").append(i + 1).append(":\n");
output.append(" ID: ").append(id).append("\n");
output.append(" नाम: ").append(name).append("\n");
output.append(" वेतन: ₹").append(String.format("%,.0f", salary)).append("\n");
output.append(" विभाग: ").append(department).append("\n\n");
}
// विभागवार गणना (बोनस)
output.append("--- विभागवार सारांश ---\n");
// ... अतिरिक्त प्रोसेसिंग यहाँ
tvJsonResult.setText(output.toString());
} catch (JSONException e) {
e.printStackTrace();
tvJsonResult.setText("JSON पार्सिंग त्रुटि: " + e.getMessage());
}
}
}
मुख्य JSON क्लासेज और मेथड्स
| क्लास/मेथड | उपयोग |
|---|---|
JSONObject(String) | JSON स्ट्रिंग से ऑब्जेक्ट बनाएं |
getJSONArray("key") | कुंजी से JSONArray प्राप्त करें (अपवाद फेंकता है यदि नहीं मिला) |
optJSONArray("key") | कुंजी से JSONArray प्राप्त करें (नल लौटाता है यदि नहीं मिला) - सुरक्षित |
getJSONObject(index) | इंडेक्स पर JSONObject प्राप्त करें |
optString("key", "default") | स्ट्रिंग मान प्राप्त करें, डिफ़ॉल्ट के साथ |
optInt("key", default) | इंट मान प्राप्त करें, डिफ़ॉल्ट के साथ |
optDouble("key", default) | डबल मान प्राप्त करें, डिफ़ॉल्ट के साथ |
optBoolean("key", default) | बूलियन मान प्राप्त करें, डिफ़ॉल्ट के साथ |
has("key") | कुंजी मौजूद है या नहीं जांचें |
isNull("key") | मान नल है या नहीं जांचें |
नेस्टेड JSON ऑब्जेक्ट्स और एरे
// नेस्टेड संरचना उदाहरण
String nestedJson = "{ \"company\": { \"departments\": [ { \"name\": \"IT\", \"employees\": [ {...} ] } ] } }";
JSONObject root = new JSONObject(nestedJson);
JSONObject company = root.getJSONObject("company");
JSONArray departments = company.getJSONArray("departments");
for (int i = 0; i < departments.length(); i++) {
JSONObject dept = departments.getJSONObject(i);
String deptName = dept.getString("name");
JSONArray employees = dept.getJSONArray("employees");
// ... आगे प्रोसेस करें
}
JSON एरे से मॉडल ऑब्जेक्ट्स बनाना
// डेटा क्लास
data class Employee(
val id: String,
val name: String,
val salary: Double,
val department: String
)
// पार्सिंग फंक्शन
fun parseEmployees(jsonString: String): List {
val employees = mutableListOf()
val root = JSONObject(jsonString)
val array = root.getJSONArray("employees")
for (i in 0 until array.length()) {
val obj = array.getJSONObject(i)
employees.add(Employee(
id = obj.optString("id"),
name = obj.optString("name"),
salary = obj.optDouble("salary", 0.0),
department = obj.optString("department")
))
}
return employees
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.app.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
बेस्ट प्रैक्टिसेज
- हमेशा opt* मेथड्स उपयोग करें (optString, optInt, आदि) - ये नल/अनुपस्थित कुंजियों को ग्रेसफुली हैंडल करते हैं
- try-catch ब्लॉक में पार्सिंग लपेटें
- बड़े JSON के लिए Gson या Moshi लाइब्रेरी का उपयोग करें - स्वचालित मैपिंग, बेहतर परफॉरमेंस
- बैकग्राउंड थ्रेड पर पार्सिंग करें (कोरूटीन/RxJava) यदि JSON बड़ा हो
आधुनिक विकल्प: प्रोडक्शन ऐप्स मेंGson(implementation 'com.google.code.gson:gson:2.10.1') याMoshiका उपयोग करें। ये POJO/डेटा क्लासेज में स्वचालित मैपिंग, नल सेफ्टी, और बेहतर एरर हैंडलिंग प्रदान करते हैं।