How to parse json in android

JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server.

In this tutorial we are going to learn how to parse JSON in android using different ways, using java.net library and other third part libraries.


In This Tutorial We Can Parse A Simple Json Data Which Shows The Name Of The Cities From The Server

I use My Own Created JSON File Which is Live On The Server U See By Click On The Url Shown Below


You Can Create Your Own JSON File On myjson.com


 AndroidManifest.xml

  In This File We Have To Insert An Permission Of Internet

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

<uses-permission android:name="android.permission.INTERNET"/>

<application  
 android:allowBackup="true"         
 android:icon="@mipmap/ic_launcher"         
 android:label="@string/app_name"         
 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>
<activity android:name=".button"/>
</application>
</manifest
 
 

 HttpHandler.java

  In This Class We Make Service Call() Makes HTTP Call To Particular Url And Fetches The Cities Name

 

package com.tushar.jsonparsing;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/** * Created by Lenovo on 7/29/2017. */
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler(){}

public String makeServiceCall(String reqUrl){
String response = null;

try {
URL url = new URL(reqUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = new BufferedInputStream(connection.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return response;
}

private String convertStreamToString(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine())!=null){
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

}
 
 

 ActivityMain.xml

<?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="com.tushar.jsonparsing.MainActivity">

<ListView  
 android:id="@+id/list" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent"         
 android:layout_alignParentBottom="true"         
 android:layout_alignParentEnd="true" />
</RelativeLayout>
 
 

 

ListItem.xml

If You Are Not Know About List View Check Out Our List View Tut For Android
 
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"     
 android:orientation="vertical"  
 android:layout_width="match_parent" 
 android:layout_height="match_parent">

<TextView 
 android:text="TextView" 
 android:layout_width="match_parent"         
 android:layout_height="wrap_content"         
 android:id="@+id/name" 
 android:paddingTop="6dp"         
 android:paddingBottom="2dp"         
 android:textColor="@color/colorPrimaryDark" 
 android:textSize="16sp" 
 android:textStyle="bold"        />
</LinearLayout>

MainActivity.java

As we are getting the JSON by making HTTP call, I am adding a Async class GetContacts to make http calls on background thread. Add the following method in your main activity class.
 
package com.tushar.jsonparsing;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

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

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog progressDialog;
private ListView lv;
private static String url = "http://api.myjson.com/bins/sh0id";
ArrayList<HashMap<String,String>> cityList;
@Override 
 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

cityList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetCities().execute();


}
private class GetCities extends AsyncTask<Void,Void,Void>{
@Override 
 protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog  
            progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Connecting To Server...");
progressDialog.setCancelable(false);
progressDialog.show();

}

@Override  
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();

// Making a request to url and getting response  
String jsonStr = sh.makeServiceCall(url);

Log.e(TAG, "Response from url: " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node 
 JSONArray cities = jsonObj.getJSONArray("cities");

// looping through All Contacts  
for (int i = 0; i < cities.length(); i++) {
JSONObject c = cities.getJSONObject(i);


String name = c.getString("name");



// tmp hash map for single contact 
 HashMap<String, String> contact = new HashMap<>();

// adding each child node to HashMap key => value
contact.put("name", name);

// adding contact to contact list 
 cityList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override 
 public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});

}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override 
 public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});

}

return null;
}

@Override 
 protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog 
 if (progressDialog.isShowing())
progressDialog.dismiss();
/** * Updating parsed JSON data into ListView * */ 
 ListAdapter adapter = new SimpleAdapter(
MainActivity.this, cityList,
R.layout.list_item, new String[]{"name"}, new int[]{R.id.name});

lv.setAdapter(adapter);
}

}
}
 
 

 

 Run Your App Using Emulator

Komentar

Postingan Populer