`
zxl_ong
  • 浏览: 126732 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

JSON对象操作

阅读更多
数据样本:
[{
    results:
    {
        itemCount:100,
        startIndex:10,
        currentCount:2,
        item:
        [
            {
                buyerId:234,
                buyerTime:'1245785214',
                price:3.0,
                buyerNickName:'sdf',
buyerIconUrl:’http://safasdfasdf’
            },
            {
                buyerId:234,
                buyerTime:'1245785214',
                price:3.0,
                buyerNickName:'sdf',
buyerIconUrl:’http://safasdfasdf’
            }
        ]
    }
}]


JSON实现:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.json);
        
        TextView tv01 = (TextView)findViewById(R.id.tv01);
        TextView tv02 = (TextView)findViewById(R.id.tv02);
        
        try {
			JSONObject jo1 = new JSONObject();
			jo1.put("buyerId", 123);
			jo1.put("buyerTime", "'1245785214'");
			jo1.put("price", 3.0);
			jo1.put("buyerNickName", "'aaaa'");
			
			JSONObject jo2 = new JSONObject();
			jo2.put("buyerId", 234);
			jo2.put("buyerTime", "'1111332222'");
			jo2.put("price", 4.0);
			jo2.put("buyerNickName", "'bbbb'");
			
			JSONArray jarr1 = new JSONArray();
			jarr1.put(jo1);
			jarr1.put(jo2);
			
			JSONObject jo3 = new JSONObject();
			jo3.put("itemCount", 100);
			jo3.put("startIndex", 10);
			jo3.put("currentCount", 2);
			jo3.put("item", jarr1);
			
			JSONObject jo4 = new JSONObject();
			jo4.put("results", jo3);
			
			JSONArray jarr2 = new JSONArray();
			jarr2.put(jo4);
			
			tv01.setText(jarr2.toString());
			
			JSONObject json = jarr2.getJSONObject(0);
			
			tv02.setText(json.getString("results"));
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}


应用JSONObject存储Map类型数值:
public static JSONObject getJSON(Map map) {
    Iterator iter = map.entrySet().iterator();
    JSONObject holder = new JSONObject(); 
 
    while (iter.hasNext()) {
        Map.Entry pairs = (Map.Entry) iter.next();
        String key = (String) pairs.getKey();
        Map m = (Map) pairs.getValue();
        JSONObject data = new JSONObject(); 
 
        try {
            Iterator iter2 = m.entrySet().iterator();
            while (iter2.hasNext()) {
                Map.Entry pairs2 = (Map.Entry) iter2.next();
                data.put((String) pairs2.getKey(), (String) pairs2.getValue());
            }
            holder.put(key, data);
        } catch (JSONException e) {
            Log.e("Transforming", "There was an error packaging JSON",e);
        }
    } 
 
    return holder;
}
                                                                                  
分享到:
评论
1 楼 Neao 2010-08-24  
嗯,写得还不错,最近做个项目一直使用JSON对象封包解包。

相关推荐

Global site tag (gtag.js) - Google Analytics