Android json操作之取得一个对象

1:服务端返回的json数据格式如下:

{"id":"1001","name":"zhangsan","score":"98"}

2:MainActivity.java中:

class GetInfoThread implements Runnable{
        public void run(){
            String url="http://192.168.0.116/android/json_test.php";
            String jsonStr=getStringFromNet(url);
            try {
                JSONObject jsonObj=new JSONObject(jsonStr);
                String id=jsonObj.getString("id");
                String name=jsonObj.getString("name");
                String score=jsonObj.getString("score");
                
                String info="ID:"+id+",Name:"+name+",Score:"+score;
                
                myHandler.obtainMessage(100, info).sendToTarget();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

3:运行结果:

4:如果服务端返回的数据格式如下:

{"student":{"id":"1001","name":"lisi"}}

则处理方法如下:

class GetInfoThread implements Runnable{
        public void run(){
            String url="http://192.168.0.116/android/json_test.php";
            String jsonStr=getStringFromNet(url);
            try {
                JSONObject jsonObj=new JSONObject(jsonStr).getJSONObject("student");
                
                String id=jsonObj.getString("id");
                String name=jsonObj.getString("name");
                
                String info="ID:"+id+",Name:"+name;
                
                myHandler.obtainMessage(100, info).sendToTarget();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

 

posted @ 2013-10-15 09:49  yshy  阅读(379)  评论(0编辑  收藏  举报