Advantage of JSON over XML
1) JSON is faster and easier than xml for AJAX applications.2) Unlike XML, it is shorter and quicker to read and write.
3) It uses array.
Example of android JSON parsing
activity_main.xmlDrag the one textview from the pallete. Now the activity_main.xml file will look like this:
<RelativeLayout xmlns:androclass="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=".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>
Activity class
Let's write the code to parse the xml using dom parser.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";
@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();}
}
}
No comments:
Post a Comment