蓝少泽

天生我材必有用,千金散去还复来。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

 

Android JSON

 
  1. package sn.len.json;  
  2.   
  3. import org.json.JSONArray;  
  4. import org.json.JSONException;  
  5. import org.json.JSONObject;  
  6.   
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.util.Log;  
  10.   
  11. public class JSONActivity extends Activity {  
  12.     private String jsondata;  
  13.     @Override  
  14.     public void onCreate(Bundle savedInstanceState)   
  15.     {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.         try   
  19.         {  
  20.             //调用构建JSON字符串方法   
  21.             buildJson();  
  22.         }  
  23.         catch (JSONException e)   
  24.         {  
  25.             e.printStackTrace();  
  26.         }  
  27.     }  
  28.     //构建JSON字符串   
  29.     public void buildJson() throws JSONException  
  30.     {  
  31.         JSONArray json=new JSONArray();  
  32.         JSONObject jsonObj=new JSONObject();  
  33.         for(int i=0;i<2;i++)  
  34.         {  
  35.             jsonObj.put("id""001");  
  36.             jsonObj.put("age""20");  
  37.             jsonObj.put("name""snoanw");  
  38.             //把每个数据当作一对象添加到数组里   
  39.             json.put(jsonObj);  
  40.         }  
  41.         jsondata=json.toString();  
  42.         Log.i("JSON", jsondata);  
  43.         //调用解析JSON方法   
  44.         parserJson(jsondata);  
  45.     }  
  46.     // 解析JSON字符串   
  47.     public void parserJson(String jsondata) throws JSONException  
  48.     {  
  49.         //构建JSON数组对象   
  50.         JSONArray json1=new JSONArray(jsondata);  
  51.         for(int i=0;i<json1.length();i++)  
  52.         {  
  53.             JSONObject jsonObj2=json1.optJSONObject(i);  
  54.             String id=jsonObj2.getString("id");  
  55.             String age=jsonObj2.getString("age");  
  56.             String name=jsonObj2.getString("name");  
  57.             Log.i("JSONDATA", id+age+name);  
  58.         }  
  59.     }  
  60. }  

 

posted on 2012-12-25 11:27  蓝少泽  阅读(180)  评论(0编辑  收藏  举报