Parsing a JsonArray in Android
In the previous part of the Json series , we seen the complete basics of json.In this part we are going to actually parse a sample Json Array.The Json will be passed aa a String within the code itself instead of caaling the external URL through HTTP call.Lets get started.
The sample json we created for todays project[Footballmania]
{
"FIFA World cup 2015":[
{
"Team_Code":"BRA",
"Team_Name":"BRAZIL",
"GOAL":"2"
},
{
"Team_Code":"GER"
"Team_Name":"GERMANY"
"GOAL":"1"
}
]
};
The difference between [ and { - (Square brackets and Curly brackets) has been completely explained in the last post of Json.so take a look at that before you proceed.
If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.
Creating New Android Project[FootballMania]
1. Create a new project in Eclipse from File ->New -> Android Application Project. I had left my main activity name as MainActivity.java and gave the package name as com.example.androidgreeve.simplejson2.Since we are not making any HTTP calls in this part of tutorial,we will make no changes to the Manifest.xml file.
Manifest.XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidgreeve.simplejson"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidgreeve.simplejson.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>
Creating the Layout
3.Now will create the required Front End for the todays project in activity_main.xml<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"
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=".MainActivity"
android:background="@drawable/bg">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="Androidgreeve"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff"
android:textStyle="bold"
android:textSize="30sp"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:text="FIFA -Final Scoreline"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff"
android:textSize="20sp" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView3"
android:layout_marginTop="54dp"
android:text="Code"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textView2"
android:layout_marginTop="60dp"
android:text="Team"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff"
android:textSize="15sp" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
android:layout_alignBottom="@+id/textView4"
android:layout_centerHorizontal="true"
android:text="Score"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#fff" />
</RelativeLayout>
Parsing the Json data.
//passing json Array as string.4.String strJson="{ \"FIFA World cup 2015\" " +
":[{\"Team_Code\":\"BRA\"," +
"\"Team_Name\":\"BRAZIL\"," +
"\"GOAL\":\"2\"}," +
"" +
"{\"Team_Code\":\"GER\"," +
"\"Team_Name\":\"GERMANY\"," +
"\"GOAL\":\"1\"}] }";
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("FIFA World cup 2015");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String Team_Code = jsonObject.optString("Team_Code").toString();
String Team_Name = jsonObject.optString("Team_Name").toString();
int GOAL = Integer.parseInt(jsonObject.optString("GOAL").toString());
Complete Code of Mainactivity.java
6. The complete code of the Main_activitypackage com.example.androidgreeve.simplejson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView T_name= (TextView)findViewById(R.id.textView3);
TextView T_Code= (TextView)findViewById(R.id.textView4);
TextView T_goal=(TextView)findViewById(R.id.textView5);
String strJson="{ \"FIFA World cup 2015\" " +
":[{\"Team_Code\":\"BRA\"," +
"\"Team_Name\":\"BRAZIL\"," +
"\"GOAL\":\"2\"}," +
"" +
"{\"Team_Code\":\"GER\"," +
"\"Team_Name\":\"GERMANY\"," +
"\"GOAL\":\"1\"}] }";
try {
// Create the root JSONObject from the JSON string.
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("FIFA World cup 2015");
String name="",code="";
String goal="";
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String Team_Code = jsonObject.optString("Team_Code").toString();
String Team_Name = jsonObject.optString("Team_Name").toString();
int GOAL = Integer.parseInt(jsonObject.optString("GOAL").toString());
name+=Team_Name+" ";
code+=Team_Code+"\n";
goal+=GOAL+"\n";
//Setting data to XML
T_name.setText(name);
T_Code.setText(code+"\n");
T_goal.setText(goal+"\n");
}
//output.setText(data);
} catch (JSONException e) {e.printStackTrace();}
}
}
Whats Next?
7.No worries, this was the simplest method to parse data.In the next tutorial we will parse Json URl anfd fetch data from it.Dont miss any thing Just subscribe and Share it.
Happy developing!Happy Coding.
7 comments
Good Article. How About Extends ActionBarActivity?
Good article!! Continue the series with lots more
Make it coming more such post ! awesome keep it up man
@Venky Nice post plz continue the series
Eagerly waiting for next post !
Nice .. post Very basic .. some more advance post please
keep posting from basic to advance sir ! I loved the series
EmoticonEmoticon