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

Android में JSON ऑब्जेक्ट्स कैसे पार्स करें?

Android में JSON पार्स करके RecyclerView में दिखाने का गाइड

यह ट्यूटोरियल दिखाता है कि कैसे assets फोल्डर से JSON फ़ाइल पढ़कर, JSONObject/JSONArray से डेटा निकालकर RecyclerView में CardView के साथ प्रदर्शित किया जाए।

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

Android Studio में File → New Project चुनकर नया प्रोजेक्ट बनाएं।

चरण 2: build.gradle में निर्भरताएं जोड़ें

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation "com.android.support:recyclerview-v7:28.0.0"
    implementation 'com.android.support:cardview-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

चरण 3: मुख्य लेआउट (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

चरण 4: रो लेआउट (rowlayout.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:card_view="https://schemas.android.com/apk/res-auto"
    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">
        <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="9999999999"
            android:textColor="#000"
            android:textSize="15sp" />
    </LinearLayout>
</android.support.v7.widget.CardView>

चरण 5: MainActivity.java

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayList<String> personNames = new ArrayList<>();
    ArrayList<String> emailIds = new ArrayList<>();
    ArrayList<String> mobileNumbers = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        try {
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray userArray = obj.getJSONArray("users");
            for (int i = 0; i < userArray.length(); i++) {
                JSONObject userDetail = userArray.getJSONObject(i);
                personNames.add(userDetail.getString("name"));
                emailIds.add(userDetail.getString("email"));
                JSONObject contact = userDetail.getJSONObject("contact");
                mobileNumbers.add(contact.getString("mobile"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        CustomAdapter customAdapter = new CustomAdapter(this, personNames, emailIds, mobileNumbers);
        recyclerView.setAdapter(customAdapter);
    }

    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = getAssets().open("users_list.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }
}

चरण 6: CustomAdapter.java

package com.example.sample;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
    ArrayList<String> personNames, emailIds, mobileNumbers;
    Context context;

    public CustomAdapter(Context context, ArrayList<String> personNames,
                         ArrayList<String> emailIds, ArrayList<String> mobileNumbers) {
        this.context = context;
        this.personNames = personNames;
        this.emailIds = emailIds;
        this.mobileNumbers = mobileNumbers;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        holder.name.setText(personNames.get(position));
        holder.email.setText(emailIds.get(position));
        holder.mobileNo.setText(mobileNumbers.get(position));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, personNames.get(position), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() { return personNames.size(); }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView name, email, mobileNo;
        public MyViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tvName);
            email = itemView.findViewById(R.id.tvEmail);
            mobileNo = itemView.findViewById(R.id.tvMobile);
        }
    }
}

चरण 7: assets/users_list.json बनाएं

{
  "users": [
    {
      "name": "John Doe",
      "email": "john@example.com",
      "contact": { "mobile": "9876543210" }
    },
    {
      "name": "Jane Smith",
      "email": "jane@example.com",
      "contact": { "mobile": "9876543211" }
    }
  ]
}

चरण 8: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.sample">
    <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>

ऐप चलाएं

डिवाइस कनेक्ट करें, Run आइकन पर क्लिक करें और JSON डेटा से भरा RecyclerView देखें।

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

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

  1. Android ऐप में Volley लाइब्रेरी से JSON कैसे पार्स करें? Android ऐप में Volley लाइब्रेरी से JSON कैसे पार्स करें?

    Volley लाइब्रेरी से JSON पार्सिंग यह उदाहरण दर्शाता है कि Google की Volley लाइब्रेरी का उपयोग करके नेटवर्क से JSON डेटा कैसे प्राप्त करें और पार्स करें। चरण 1: नया प्रोजेक्ट बनाएं Android Studio में File → New Project से प्रोजेक्ट बनाएं। चरण 2: build.gradle में Volley डिपेंडेंसी जोड़ें dependencie

  1. एंड्रॉइड में JSON एरे को कैसे इटरेट करें एंड्रॉइड में JSON एरे को कैसे इटरेट करें

    org.json लाइब्रेरी का उपयोग करके JSON एरे पार्स करना और इटरेट करना एंड्रॉइड में बिल्ट-इन org.json पैकेज (JSONArray, JSONObject) का उपयोग करके JSON डेटा पार्स किया जा सकता है। यह उदाहरण एक JSON स्ट्रिंग से एरे निकालकर उसे लूप के माध्यम से प्रोसेस करना दिखाता है। चरण 1: नया प्रोजेक्ट बनाएं Android St