android 数据传输之JSON

本文详细介绍了如何在Android应用中使用JSON数据进行对象和数组操作,包括对象创建、属性获取及数组遍历等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。

对json就不做大篇幅的介绍了。有关json的内容请自己学习。

现在说一下。json在android 的应该。

单个对象:

	void buildObject()   
	{   
	    String staticObject = "{\"firstname\":\"Steve\",\"lastname\":\"Jobs\",\"cellphones\":\"0\"}";
	    try   
	    {   
			JSONObject obj = new JSONObject(staticObject);   
	        String x = obj.get("firstname").toString() + " " + obj.get("lastname").toString() + " has " + obj.getInt("cellphones") + " Android phones.";
	        Log.i("json",x);
	    }   
	    catch (JSONException je)   
	    {   
	    }   
	   
	} 
数组对象:
	void buildJson(){
	      
	        try {
	        	InputStream is = getAssets().open("json.xml");
	            byte [] buffer = new byte[is.available()] ; 
	            is.read(buffer);
	            String json = new String(buffer,"utf-8");   
	            JSONArray roomPicNumUrlArray = new JSONArray(json);
                for(int j =0; j < roomPicNumUrlArray.length(); j++){
                    JSONObject roomPicNumUrlObject = roomPicNumUrlArray.getJSONObject(j);
                    String firstName = roomPicNumUrlObject.get("firstName").toString();
                    String lastName = roomPicNumUrlObject.get("lastName").toString();
                    String email = roomPicNumUrlObject.get("email").toString();
                    Log.i("person","firstName:"+firstName+"\tlastName:"+lastName+"\temail:"+email);
                }
	            
	            
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}

json.xml 文件保存到assets包下:

[
{"firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{"firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},
{"firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
]
结果图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值