Thursday 17 December 2015

Android - JSON Parser

JSON Parser


JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. 

This chapter explains how to parse the JSON file and extract necessary information from it.

Android provides four different classes to manipulate JSON data. 

These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.

The first step is to identify the fields in the JSON data . In the JSON given below. 


For example: 

http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php


{"Users":
[
{"firstname":"Mike","lastname":"Dalisay","username":"mike143"},

{"firstname":"Jemski","lastname":"Panlilios","username":"jemboy09"},

{"firstname":"Darwin","lastname":"Dalisay","username":"dada08"},

{"firstname":"Jaylord","lastname":"Bitamug","username":"jayjay"},

{"firstname":"Justine","lastname":"Bongola","username":"jaja"},

{"firstname":"Jun","lastname":"Sabayton","username":"jun"},

{"firstname":"Lourd","lastname":"De Veyra","username":"lourd"},

{"firstname":"Asi","lastname":"Taulava","username":"asi"},

{"firstname":"James","lastname":"Yap","username":"james"},

{"firstname":"Chris","lastname":"Tiu","username":"chris"},

{"firstname":"xxxrrr","lastname":"xxxrrr","username":"xxrrr"}
]}


JSON - Elements:

An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −

 


Component & description

Array([) In a JSON file , square bracket ([) represents a JSON array

Objects({) In a JSON file, curly bracket ({) represents a JSON object

Key A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object

Value Each key has a value that could be string , integer or double e.t.c

JSON - Parsing:

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is:

String s;
JSONObject jsonObject=new JSONObject(s);
JSONArray jsonArray=jsonObject.getJSONArray("Users"); 
 
 
 
The last step is to parse the JSON.

An JSON file consist of different object with different key/value pair e.t.c.

 So JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below:

jsonArray.getJSONObject().getString("firstname");
jsonArray.getJSONObject().getString("username");
jsonArray.getJSONObject().getString("lastname") 
 


 
The method getJSONObject returns the JSON object. The method getString returns the string value of the specified key.

Apart from the these methods , there are other methods provided by this class for better parsing JSON files. These methods are listed below −
 
 
Method & description:
 



get(String name) This method just Returns the value but in the form of Object type

getBoolean(String name) This method returns the boolean value specified by the key

getDouble(String name) This method returns the double value specified by the key


getInt(String name) This method returns the integer value specified by the key

getLong(String name) This method returns the long value specified by the key

length() This method returns the number of name/value mappings in this object..

names() This method returns an array containing the string names in this object.

Example

To experiment with this example , you can run this on an actual device or in an emulator.


Here, I have Student details json and i download all student details using Asynctask for that i create pojo class and i put in to the listview for that i create Adapter class.In manifest need INTERNET Permission.



MainActivity:

package com.example.root.studentjson;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;


public class MainActivity extends ActionBarActivity {
    Button getlist_bt;
    ListView list;
    MyAsync async;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getlist_bt=(Button)findViewById(R.id.button);
        list=(ListView)findViewById(R.id.listView);
        getlist_bt.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                async= new MyAsync(MainActivity.this,list);
                async.execute("http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php");

            }
        });
    }

    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();

        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

MyAdapter:

package com.example.root.studentjson;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/** * Created by root on 9/12/15. */public class MyAdapter extends BaseAdapter {
    Context c;
    ArrayList<Users> al;
    LayoutInflater layoutInflater;

    public MyAdapter(Context c, ArrayList<Users> al) {
        this.c = c;
        this.al = al;
        layoutInflater=LayoutInflater.from(c);
    }

    @Override    public int getCount() {

        return al.size();
    }

    @Override    public Object getItem(int position) {
        return null;
    }

    @Override    public long getItemId(int position) {
        return 0;
    }

    @Override    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null)
        {
            convertView=layoutInflater.inflate(R.layout.item_list,parent,false);
        }
        TextView firstname_tv=(TextView)convertView.findViewById(R.id.firstname);
        TextView username_tv=(TextView)convertView.findViewById(R.id.username);
        TextView lastname_tv=(TextView)convertView.findViewById(R.id.lastname);
        firstname_tv.setText(al.get(position).getFirstname());
        username_tv.setText(al.get(position).getUsername());
        lastname_tv.setText(al.get(position).getLastname());

        return convertView;
    }
}

MyAsync:
 
package com.example.root.studentjson;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

/** * Created by root on 9/12/15. */public class MyAsync extends AsyncTask<String,String ,String > {
    Context c;
    ListView list;
    MyAdapter adapter;
    ProgressDialog pd;

    public MyAsync(Context c, ListView list) {
        this.c = c;
        this.list = list;
    }

    @Override    protected String doInBackground(String... params) {
        try {
            URL url=new URL(params[0]);
            HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
            httpURLConnection.connect();
            InputStream inputStream=httpURLConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            br.close();
            return sb.toString();


        }catch (Exception e){

        }
        return null;
    }

    @Override    protected void onPostExecute(String s) {

        super.onPostExecute(s);
        try {
            ArrayList<Users> arrayList=new ArrayList<>();
            JSONObject jsonObject=new JSONObject(s);
            JSONArray jsonArray=jsonObject.getJSONArray("Users");
            for (int i=0;i<jsonArray.length();i++){


                Users users=new Users(jsonArray.getJSONObject(i).getString("firstname"),jsonArray.getJSONObject(i).getString("username"),jsonArray.getJSONObject(i).getString("lastname"));
                arrayList.add(users);
            }
            adapter=new MyAdapter(c,arrayList);
            list.setAdapter(adapter);
            pd.dismiss();

        }catch (Exception e){

        }
    }

    @Override    protected void onPreExecute() {
        pd=new ProgressDialog(c);
        pd.setMessage("downloading json");
        pd.show();
        super.onPreExecute();
    }

    @Override    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }
}
 
Users:
 
package com.example.root.studentjson;

/** * Created by root on 9/12/15. */public class Users {
    String firstname,username,lastname;

    public Users(String firstname, String username, String lastname) {
        this.firstname = firstname;
        this.username = username;
        this.lastname = lastname;
    }

    public String getFirstname() {

        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}
Manifest:

 
 
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.root.studentjson" >
    <uses-permission android:name="android.permission.INTERNET">

    </uses-permission>

    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >
        <activity            android:name=".MainActivity"            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Can you run this code, you will get student details list show in listview. 









             















 

 

 

 

 

 

 

0 comments:

Post a Comment