Skip to content Skip to sidebar Skip to footer

How to Save and Read Json Android Studio

JSON Parsing Tutorial With Example In Android Studio [Step by Stride]

JSON stands for JavaScript Object Notation. Information technology is structured, low-cal weight, man readable and piece of cake to parse. It'south a best alternative to XML when our android app needs to interchange information from server. XML parsing is very complex as compare to JSON parsing.

JSON is shorter, quicker and easier way to interchange data from server. JSON is great success and most of the API available support JSON format.

Android Provide us four unlike classes to dispense JSON data. These classes are JSONObject, JSONArray, JSONStringer and JSONTokenizer.


Sample JSON format:

Below is the sample code of JSON. Its very elementary JSON code which gives us the listing of users where each object contain the information like user id, name, email, gender and dissimilar contact numbers.

          {     "users": [         {                 "id": "1087",                 "name": "Abhishek Saini",                 "email": "info@abhiandroid.com",                 "gender" : "male",                 "contact": {                     "mobile": "+91 0000000000",                     "home": "00 000000",                     "role": "00 000000"                 }         },         {                 "id": "1088",                 "name": "Gourav",                 "email": "gourav9188@gmail.com",                 "gender" : "male",                 "contact": {                     "mobile": "+91 0000000000",                     "home": "00 000000",                     "function": "00 000000"                 }         },         .         .         .         .   ] }

JSON Elements In Android:

In Android, JSON consist of many components. Below we ascertain some common components.

ane. Array([): In a JSON, square bracket ([) represents a JSONArray. JSONArray values may exist any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or Zip. Values may not be NaNs, infinities, or of whatsoever type non listed here.

2. Objects({): In a JSON, curly subclass ({) represents a JSONObject. A JSONObject represents the data in the form of key and value pair. JSONObject values may exist whatever mix of other JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values may not be NaNs, infinities, or of any type not listed here.

3. key: A JSONObject contains a key that is in string format. A pair of key and value creates a JSONObject.

4. Value: Each central has a value that could exist archaic datatype(integer, float, Cord etc).


JSON Parsing In Android:

Usually, JSON incorporate ii types of nodes JSONArray and JSONObject so while parsing nosotros take to use the advisable method. If JSON starts from square bracket ([) we use getJSONArray() method and if it start from curly bracket ({) then we should use the getJSONObject() method. Apart from these there are another methods for amend parsing JSON data.


JSONObjet Parsing methods:

Below we define some important methods of JSONObject parsing which are mainly used for parsing the data from JSONObject.

ane. get(String proper noun): This method is used to get the value from JSONObject. It returns the value of object type. We pass the String blazon cardinal and it returns the value of Object type if exists otherwise it throws JSONException.

2. getBoolean(String name): This method is used to become the Boolean value from JSONObject. We pass the String type key and information technology returns the value of Boolean type if exists otherwise it throws JSONException.

three. getDouble(String name): This method is used to get the double blazon value from JSONObject. Nosotros pass the String type primal and it returns the value in double type if exists otherwise information technology throws JSONException.

four. getInt(String name): This method is used to get the int blazon value from JSONObject. We pass the string type key and it returns the value in int type if exists otherwise it throws JSONException.

5. getJSONArray(String name): This method is used to get the JSONArray type value. We pass the String type key and it returns JSONArray if exists otherwise it throws JSONException.

6. getJSONObject(Cord name): This method is used to get the JSONObject type value. We laissez passer the String type central and it returns the JSONObject value if exists otherwise it throws JSONException.

7. getLong(String proper name): This method is used to get the long blazon value from JSONObject. We pass the Cord blazon central and it returns the value in long blazon if exists otherwise it throws JSONException.

8. getString(Cord proper noun): This method is used to get the String type value from JSONObject. We pass the String type key and it returns the value in Cord type if exists otherwise it throws JSONException.

9. length(): This method is used to go the number of name/value mappings in this object.

x. keys(): This method is used to go the iterator of String names in the Object.

11. opt(String name): This method is used to get the value from JSONObject. It returns the value of Object blazon. We pass the String type primal and it returns the value of Object blazon if exists otherwise it returns zip.

12. optBoolean(String proper name): This method is used to get the Boolean value from JSONObject. We laissez passer the Cord type primal and it returns the value of Boolean type if exists otherwise it returns imitation.

13. optDouble(String proper name): This method is used to get the double type value from JSONObject. We pass the String type key and information technology returns the value in double type if exists otherwise information technology returns NaN.

fourteen. optInt(String name): This method is used to become the int type value from JSONObject. Nosotros laissez passer the string type fundamental and it returns the value in int blazon if exists otherwise it returns 0.

15. optJSONArray(String name): This method is used to go the JSONArray blazon value from JSONObject. We pass the String blazon primal and it returns JSONArray if exists otherwise it returns cypher.

16. optJSONObject(String proper name): This method is used to go the other JSONObject type value from JSONObject. We laissez passer the String type fundamental and it returns the JSONObject value if exists otherwise it returns zilch.

17. optLong(String name): This method is used to get the long type value from JSONObject. We pass the String type central and it returns the value in long type if exists otherwise it returns 0.

18. optString(String name): This method is used to get the String type value from JSONObject. We pass the String blazon primal and information technology returns the value in String blazon if exists otherwise it returns emptly("") string.


JSONArray Parsing methods:

Below nosotros define some important methods of JSONArray parsing which are mainly used for parsing the data from JSONArray.

1. become(int index): This method is used to become the value from JSONArray. It returns the value of object blazon. We laissez passer the index and it returns the value of object type if be otherwise information technology throws JSONException.

ii. getBoolean(int index): This method is used to get the Boolean value from JSONArray. Nosotros pass the alphabetize and information technology returns the value of Boolean type if exists otherwise it throws JSONException.

three. getDouble(int index): This method is used to go the double type value from JSONArray. We pass the index and information technology returns the value in double type if exists otherwise it throws JSONException.

4. getInt(int index): This method is used to become the int type value from JSONArray. We pass the index and it returns the value in int blazon if exists otherwise information technology throws JSONException.

5. getJSONArray(int index): This method is used to get the JSONArray blazon value. We laissez passer the alphabetize and information technology returns JSONArray if exists otherwise it throws JSONException.

6. getJSONObject(int index): This method is used to get the JSONObject blazon value. Nosotros pass the index and it returns the JSONObject value if exists otherwise it throws JSONException.

7. getLong(int index): This method is used to get the long blazon value from JSONArray. We pass the alphabetize and it returns the value in long type if exists otherwise it throws JSONException.

8. getString(int index): This method is used to get the String type value from JSONArray. Nosotros pass the index and it returns the value in String type if exists otherwise it throws JSONException.

9. length(): This method is used to get the number of values in this Array.

10. opt(int index): This method is used to get the value from JSONArray. It returns the value of Object blazon. We pass the index and it returns the value at index of Object type if exists otherwise it returns cypher.

xi. optBoolean(int alphabetize): This method is used to go the Boolean value from JSONArray. We pass the index and it returns the value of Boolean blazon if exists otherwise it returns faux.

12. optDouble(int index): This method is used to get the double type value from JSONArray. We pass the alphabetize and it returns the value in double type if exists otherwise information technology returns NaN.

13. optInt(int index): This method is used to get the int type value from JSONArray. We laissez passer the index and information technology returns the value in int type if exists otherwise it returns 0.

14. optJSONArray(int index): This method is used to get the other JSONArray type value from JSONArray. We pass the index and it returns JSONArray if exists otherwise it returns zilch.

15. optJSONObject(int index): This method is used to get the JSONObject type value from JSONArray. We pass the index and it returns the JSONObject value if exists otherwise information technology returns nix.

16. optLong(int index): This method is used to become the long type value from JSONArray. We pass the index and it returns the value in long type if exists otherwise it returns 0.

17. optString(int index): This method is used to get the String type value from JSONArray. We pass the index and it returns the value in String type if exists otherwise it returns empty("") string.


Example 1 ofSimple JSON Parsing In Android Studio:

Beneath is the example of JSON parsing in Android, In this case we parse the data from JSON and and so display information technology in the UI.In this, we have employee name and salary stored in JSON format. Firstly we create two TextView's in our XML file and and so in our Activity we parse the information using JSONObject methods and set it in the TextView's.

Below you can download code, see final output and step past step explanation of the example:

Download Code

JSON Parsing Example in Android Studio

Pace 1: Create a new projection and name it JSONParsingExample.

Step 2: Open res -> layout -> activity_main.xml (or) principal.xml and add following code:

In this footstep nosotros create two TextView's for displaying employee name and salary.

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context="abhiandroid.com.jsonparsingexample.MainActivity">      <TextView         android:id="@+id/name"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerHorizontal="true"         android:layout_marginTop="50dp"         android:text="Name"         android:textColor="#000"         android:textSize="20sp" />      <TextView         android:id="@+id/salary"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_centerHorizontal="true"         android:layout_marginTop="80dp"         android:text="Salary"         android:textColor="#000"         android:textSize="20sp" /> </RelativeLayout>        

Step 3 : Now open app -> java -> package -> MainActivity.coffee and add together the below lawmaking.

In this pace firstly nosotros get the reference of both TextView'south then nosotros parse the JSON using JSONObject methods and finally we ready the data in Textview's.

package abhiandroid.com.jsonparsingexample;  import android.os.Packet; import android.support.v7.app.AppCompatActivity; import android.widget.TextView;  import org.json.JSONException; import org.json.JSONObject;  public class MainActivity extends AppCompatActivity {       String JSON_STRING = "{\"employee\":{\"proper noun\":\"Abhishek Saini\",\"salary\":65000}}";     Cord name, salary;     TextView employeeName, employeeSalary;      @Override     protected void onCreate(Packet savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         // get the reference of TextView's         employeeName = (TextView) findViewById(R.id.proper name);         employeeSalary = (TextView) findViewById(R.id.salary);          try {             // get JSONObject from JSON file             JSONObject obj = new JSONObject(JSON_STRING);             // fetch JSONObject named employee             JSONObject employee = obj.getJSONObject("employee");             // become employee proper noun and salary             name = employee.getString("name");             salary = employee.getString("salary");             // ready employee name and salary in TextView's             employeeName.setText("Proper name: "+proper name);             employeeSalary.setText("Salary: "+bacon);          } catch (JSONException e) {             e.printStackTrace();         }     } }        

JSON Parsing File Example 2 In Android Studio:

Below is the 2d case of JSON parsing In Android Studio. In this case we create a JSON file and shop it in assets folder of Android. In this JSON file we have list of users where each object contain the information similar user id, proper name, e-mail, gender and dissimilar contact numbers. In this we are using LinearLayoutManager with vertical orientation to display the array items. Firstly nosotros declare a RecyclerView in our XML file and then get the reference of it in our Activity. After that we fetch the JSON file then parse the JSONArray data and finally set the Adapter to show the items in RecyclerView. Whenever a user clicks on an particular the name of the Person is displayed on the screen with the help of Toast.

Download Code

JSON Parsing File Example in Android Studio

Stride 1: Create a new project and proper name it JSONParsingExample.

Footstep 2: Open Gradle Scripts > build.gradle and add RecyclerView and CardView Library dependency in it.

apply plugin: 'com.android.application'  android {     compileSdkVersion 24     buildToolsVersion "24.0.1"      defaultConfig {         applicationId "abhiandroid.com.jsonparsingexample"         minSdkVersion 16         targetSdkVersion 24         versionCode i         versionName "1.0"     }     buildTypes {         release {             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     } }  dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     testCompile 'junit:junit:iv.12'     compile 'com.android.support:appcompat-v7:24.i.one'     compile "com.android.support:recyclerview-v7:23.0.1" // dependency file for RecyclerView     compile 'com.android.support:cardview-v7:23.0.i' // dependency file for CardView }

Footstep 3: Open res -> layout -> activity_main.xml (or) principal.xml and add following lawmaking:

In this step we create a RecyclerView in our XML file.

<?xml version="i.0" encoding="utf-viii"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context="abhiandroid.com.jsonparsingexample.MainActivity">      <android.support.v7.widget.RecyclerView         android:id="@+id/recyclerView"         android:layout_width="match_parent"         android:layout_height="match_parent" /> </RelativeLayout>        

Step 4: Create a new XML file rowlayout.xml for item of RecyclerView and paste the post-obit code in information technology.

In this step nosotros create a new xml file for detail row in which nosotros create a TextView to show the data.

          <?xml version="1.0" encoding="utf-8"?>  <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:card_view="http://schemas.android.com/apk/res-automobile"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/card_view"     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/name"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="Name"             android:textColor="#000"             android:textSize="20sp" />          <TextView             android:id="@+id/email"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="electronic mail@e-mail.com"             android:textColor="#000"             android:textSize="15sp" />          <TextView             android:id="@+id/mobileNo"             android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:text="e9999999999"             android:textColor="#000"             android:textSize="15sp" />     </LinearLayout> </android.support.v7.widget.CardView>        

Step 5 : At present open app -> coffee -> parcel -> MainActivity.java and add the below code.

In this pace firstly we go the reference of RecyclerView. After that nosotros fetch the JSON file from assets and parse the JSON data using JSONArray and JSONObject methods and then set a LayoutManager and finally we set the Adapter to show the items in RecyclerView.

package abhiandroid.com.jsonparsingexample;  import android.os.Package; import android.support.v7.app.AppCompatActivity; import android.back up.v7.widget.LinearLayoutManager; import android.back up.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 coffee.util.ArrayList; import java.util.Arrays;  public class MainActivity extends AppCompatActivity {      // ArrayList for person names, electronic mail Id's and mobile numbers     ArrayList<String> personNames = new ArrayList<>();     ArrayList<Cord> emailIds = new ArrayList<>();     ArrayList<String> mobileNumbers = new ArrayList<>();      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         // get the reference of RecyclerView         RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);         // set a LinearLayoutManager with default vertical orientation         LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());         recyclerView.setLayoutManager(linearLayoutManager);          endeavour {             // go JSONObject from JSON file             JSONObject obj = new JSONObject(loadJSONFromAsset());             // fetch JSONArray named users             JSONArray userArray = obj.getJSONArray("users");             // implement for loop for getting users list data             for (int i = 0; i < userArray.length(); i++) {                 // create a JSONObject for fetching single user data                 JSONObject userDetail = userArray.getJSONObject(i);                 // fetch e-mail and name and store it in arraylist                 personNames.add(userDetail.getString("name"));                 emailIds.add together(userDetail.getString("e-mail"));                 // create a object for getting contact data from JSONObject                 JSONObject contact = userDetail.getJSONObject("contact");                 // fetch mobile number and store it in arraylist                 mobileNumbers.add(contact.getString("mobile"));             }         } catch (JSONException eastward) {             e.printStackTrace();         }          //  telephone call the constructor of CustomAdapter to send the reference and data to Adapter         CustomAdapter customAdapter = new CustomAdapter(MainActivity.this, personNames, emailIds, mobileNumbers);         recyclerView.setAdapter(customAdapter); // fix the Adapter to RecyclerView     }      public String loadJSONFromAsset() {         String json = zippo;         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-viii");         } take hold of (IOException ex) {             ex.printStackTrace();             render zippo;         }         return json;     } }        

Footstep 6: Create a new class CustomAdapter.java inside package and add the following lawmaking.

In this step we create a CustomAdapter class and extends RecyclerView.Adapter class with ViewHolder in it. After that we implement the overrided methods and create a constructor for getting the data from Action, In this custom Adapter two methods are more important get-go is onCreateViewHolder in which nosotros inflate the layout item xml and pass it to View Holder and other is onBindViewHolder in which we gear up the data in the view'south with the assistance of ViewHolder.

package abhiandroid.com.jsonparsingexample;  import android.content.Context; import android.back up.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast;  import coffee.util.ArrayList;   public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {      ArrayList<Cord> personNames;     ArrayList<String> emailIds;     ArrayList<String> mobileNumbers;     Context context;      public CustomAdapter(Context context, ArrayList<String> personNames, ArrayList<String> emailIds, ArrayList<Cord> mobileNumbers) {         this.context = context;         this.personNames = personNames;         this.emailIds = emailIds;         this.mobileNumbers = mobileNumbers;     }      @Override     public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         // infalte the item Layout         View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);         MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder         render vh;     }      @Override     public void onBindViewHolder(MyViewHolder holder, final int position) {         // set the information in items         holder.name.setText(personNames.become(position));         holder.email.setText(emailIds.go(position));         holder.mobileNo.setText(mobileNumbers.become(position));         // implement setOnClickListener event on detail view.         holder.itemView.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 // brandish a toast with person proper noun on item click                 Toast.makeText(context, personNames.get(position), Toast.LENGTH_SHORT).bear witness();             }         });      }       @Override     public int getItemCount() {         return personNames.size();     }      public form MyViewHolder extends RecyclerView.ViewHolder {         TextView name, e-mail, mobileNo;// init the detail view's          public MyViewHolder(View itemView) {             super(itemView);              // get the reference of item view's             name = (TextView) itemView.findViewById(R.id.name);             email = (TextView) itemView.findViewById(R.id.email);             mobileNo = (TextView) itemView.findViewById(R.id.mobileNo);          }     } }        

salinasfainim.blogspot.com

Source: https://abhiandroid.com/programming/json

Post a Comment for "How to Save and Read Json Android Studio"