JSON parsing example 1
package a.b;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class Jsonparsedemo1Activity extends Activity {
TextView tv1,tv2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
// {"id":12,"name":12,"status":"ok","volumes":[{"id":17592,"name":"root","status":"ok"}]}
final String customJSON = "{\"id\":12,\"name\":12,\"status\":\"ok\",\"volumes\":[{\"id\":17592,\"name\":\"root\",\"status\":\"ok\"}]}"; // tv1.setText(customJSON);
try
{
JSONObject jobj=new JSONObject(customJSON);
String id=jobj.getString("id");
String myname=jobj.getString("name");
String status1=jobj.getString("status");
String result1="id1="+id+"\n"+"name1="+myname+"\n"+"status1"+status1;
tv1.setText(result1);
JSONArray jarray=jobj.getJSONArray("volumes");
JSONObject myobj=jarray.getJSONObject(0);
String id2=myobj.getString("id");
String myname2=myobj.getString("name");
String status2=myobj.getString("status");
String result="id2="+id2+"\n"+"name2="+myname2+"\n"+"status2"+status2;
tv2.setText(result);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(Jsonparsedemo1Activity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
No comments:
Post a Comment