JSONObject ক্লাস ব্যবহার করে JSON পার্সিং
এই উদাহরণটি দেখায় কিভাবে কোটলিন ব্যবহার করে এন্ড্রয়েডে JSONObject ক্লাস ব্যবহার করে JSON স্ট্রিং পার্স করা যায় এবং নির্দিষ্ট ফিল্ডের মান বের করা যায়।
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
Android Studio-তে File → New Project এ যান এবং প্রজেক্ট তৈরি করুন।
ধাপ ২: লেআউট XML ফাইল কনফিগার করুন
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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
ধাপ ৩: MainActivity.kt ফাইলে লজিক লিখুন
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONException
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
private val jsonString = "{\"Employee\":{\"Name\":\"Niyaz\",\"Salary\":56000}}"
lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
try {
val emp = JSONObject(jsonString).getJSONObject("Employee")
val empName = emp.getString("Name")
val empSalary = emp.getInt("Salary")
val string = "Employee Name: $empName\nEmployee Salary: $empSalary"
textView.text = string
} catch (e: JSONException) {
e.printStackTrace()
}
}
}
ধাপ ৪: AndroidManifest.xml আপডেট করুন
সাধারণ ম্যানিফেস্ট কনফিগারেশন যথেষ্ট।
অ্যাপ্লিকেশন চালানোর পদ্ধতি
ডিভাইস সংযুক্ত করে Run করুন। JSON স্ট্রিং পার্স হয়ে কর্মচারীর নাম এবং বেতন দেখাবে।