JSON Example

  • JSON :- JavaScript Object Notation
  • It contains key/value pairs
  • Key-> Strings
  • Values:->JSON
  • {}   :-> JSON Object
  • []    :-> JSON array
Syntax :
{"employees":[
    {"firstName":"John""lastName":"Doe"},
    {"firstName":"Anna""lastName":"Smith"},
    {"firstName":"Peter""lastName":"Jones"}
]}

package csdevbin.json;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

   
public static final String JSON_STRING = "{\"employee\":{\"name\":\"John\",\"salary\":6000}}";

   
@Override
   
public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);

        TextView textView1 = (TextView) findViewById(R.id.
textView1);

       
try {
            JSONObject emp = (
new JSONObject(JSON_STRING)).getJSONObject("employee");
            String empname = emp.getString(
"name");
           
int empsalary = emp.getInt("salary");

            String str =
"Employee Name:" + empname + "\n" + "Employee Salary:" + empsalary;
            textView1.setText(str);

        }
catch (Exception e) {
            e.printStackTrace();
        }

    }
}

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="csdevbin.json.MainActivity">

    <TextView

        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="46dp"
        android:text="TextView" />

</RelativeLayout>




Comments :

Post a Comment