Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Android

Kotlin का उपयोग करके Android पर JSON ऑब्जेक्ट्स कैसे पार्स करें?

परिचय

यह उदाहरण दर्शाता है कि Kotlin का उपयोग करके Android पर JSON ऑब्जेक्ट्स कैसे पार्स किए जाएं।

चरण 1: नया प्रोजेक्ट बनाएं

Android Studio खोलें, File → New Project पर जाएं और आवश्यक विवरण भरकर एक नया प्रोजेक्ट बनाएं।

चरण 2: activity_main.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">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

चरण 3: JSON एसेट फाइल बनाएं

एक नया assets फोल्डर बनाएं और user_list.json फाइल बनाएं जिसमें निम्न कोड हो:

{
    "users": [
        {
            "name": "Niyaz",
            "email": "testemail1@gmail.com",
            "contact": {
                "mobile": "+91 0000000000"
            }
        },
        {
            "name": "Azhar",
            "email": "testemail2@gmail.com",
            "contact": {
                "mobile": "+91 0000000000"
            }
        },
        {
            "name": "Mahi",
            "email": "testemail3@gmail.com",
            "contact": {
                "mobile": "+91 0000000000"
            }
        }
    ]
}

चरण 4: MainActivity.kt लागू करें

src/MainActivity.kt में निम्न कोड जोड़ें:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

class MainActivity : AppCompatActivity() {
    var personName: ArrayList<String> = ArrayList()
    var emailId: ArrayList<String> = ArrayList()
    var mobileNumbers: ArrayList<String> = ArrayList()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        val linearLayoutManager = LinearLayoutManager(applicationContext)
        recyclerView.layoutManager = linearLayoutManager
        
        try {
            val obj = JSONObject(loadJSONFromAsset())
            val userArray = obj.getJSONArray("users")
            
            for (i in 0 until userArray.length()) {
                val userDetail = userArray.getJSONObject(i)
                personName.add(userDetail.getString("name"))
                emailId.add(userDetail.getString("email"))
                val contact = userDetail.getJSONObject("contact")
                mobileNumbers.add(contact.getString("mobile"))
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        
        val customAdapter = CustomAdapter(this@MainActivity, personName, emailId, mobileNumbers)
        recyclerView.adapter = customAdapter
    }
    
    private fun loadJSONFromAsset(): String {
        var json: String? = null
        try {
            val inputStream = assets.open("users_list.json")
            val size = inputStream.available()
            val buffer = ByteArray(size)
            val charset: Charset = StandardCharsets.UTF_8
            inputStream.read(buffer)
            inputStream.close()
            json = String(buffer, charset)
        } catch (ex: IOException) {
            ex.printStackTrace()
            return ""
        }
        return json!!
    }
}

चरण 5: CustomAdapter.kt बनाएं

CustomAdapter.kt नाम से एक नई क्लास बनाएं और निम्न कोड जोड़ें:

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder

class CustomAdapter(
    private var context: Context,
    private var personNames: ArrayList<String>,
    private var emailIds: ArrayList<String>,
    private var mobileNumbers: ArrayList<String>
) : RecyclerView.Adapter<CustomAdapter.MyViewHolder>() {
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.rowlayout, parent, false)
        return MyViewHolder(v)
    }
    
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.name.text = personNames[position]
        holder.email.text = emailIds[position]
        holder.mobileNo.text = mobileNumbers[position]
        
        holder.itemView.setOnClickListener {
            Toast.makeText(context, personNames[position], Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun getItemCount(): Int {
        return personNames.size
    }
    
    inner class MyViewHolder(itemView: View) : ViewHolder(itemView) {
        var name: TextView = itemView.findViewById(R.id.tvName) as TextView
        var email: TextView = itemView.findViewById(R.id.tvEmail) as TextView
        var mobileNo: TextView = itemView.findViewById(R.id.tvMobile) as TextView
    }
}

चरण 6: row_layout.xml बनाएं

row_layout.xml नाम से एक लेआउट रिसोर्स फाइल बनाएं और निम्न कोड जोड़ें:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_margin="5dp"
    android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp">
        <!--items for a single row of RecyclerView-->
        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textColor="#000"
            android:textSize="20sp" />
        <TextView
            android:id="@+id/tvEmail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="email@email.com"
            android:textColor="#000"
            android:textSize="15sp" />
        <TextView
            android:id="@+id/tvMobile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="e9999999999"
            android:textColor="#000"
            android:textSize="15sp" />
    </LinearLayout>
</androidx.cardview.widget.CardView>

चरण 7: AndroidManifest.xml कॉन्फ़िगर करें

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

एप्लिकेशन चलाएं

अपने Android डिवाइस को कंप्यूटर से कनेक्ट करें। Android Studio में प्रोजेक्ट की एक्टिविटी फाइल खोलें और टूलबार से Run आइकन पर क्लिक करें। अपना मोबाइल डिवाइस चुनें और डिफ़ॉल्ट स्क्रीन देखें।

सुझाव: उत्पादन ऐप्स के लिए, मैन्युअल JSON पार्सिंग के बजाय Gson, Moshi, या Kotlinx.serialization जैसी लाइब्रेरी का उपयोग करने पर विचार करें।
  1. Android में JSON ऑब्जेक्ट्स कैसे पार्स करें? Android में JSON ऑब्जेक्ट्स कैसे पार्स करें?

    Android में JSON पार्स करके RecyclerView में दिखाने का गाइड यह ट्यूटोरियल दिखाता है कि कैसे assets फोल्डर से JSON फ़ाइल पढ़कर, JSONObject/JSONArray से डेटा निकालकर RecyclerView में CardView के साथ प्रदर्शित किया जाए। चरण 1: नया प्रोजेक्ट बनाएं Android Studio में File → New Project चुनकर नया प्रोजेक

  1. Android में JSON कैसे पार्स करें? Android में JSON कैसे पार्स करें?

    Android में JSONObject से सरल JSON पार्स करने का गाइड यह ट्यूटोरियल दिखाता है कि कैसे एक JSON स्ट्रिंग से JSONObject बनाकर नेस्टेड ऑब्जेक्ट्स से मान निकाले जाएं। चरण 1: नया प्रोजेक्ट बनाएं Android Studio में File → New Project चुनकर नया प्रोजेक्ट बनाएं। चरण 2: लेआउट फ़ाइल में कोड जोड़ें res/layout

  1. एंड्रॉइड में HTML कैसे पार्स करें? एंड्रॉइड में HTML कैसे पार्स करें?

    Jsoup लाइब्रेरी के साथ HTML पार्सिंग यह उदाहरण दर्शाता है कि Jsoup लाइब्रेरी का उपयोग करके वेबसाइट से HTML डाउनलोड करें और टाइटल, लिंक निकालें। चरण 1: नया प्रोजेक्ट बनाएं Android Studio में File → New Project चुनें। चरण 2: लेआउट में बटन और TextView res/layout/activity_main.xml: <?xml version=1.