日期:2014-05-16  浏览次数:20415 次

Json解析实例

?

?1. 第一种是对象里面含有数组的json格式如下:

{"audio":{"info":[{"id":1,"icon":"http:\/\/localhost\/test\/mm.jpg","name":"fm930","time":"8:00-12:00","ip":"http:\/\/192.168.3.99\/mp3\/m.mp3"},{"id":1,"icon":"http:\/\/localhost\/test\/mm.png","name":"fm950","time":"8:00-12:00","ip":"http:\/\/192.168.3.99\/mp3\/m.mp3"},{"id":1,"icon":"http:\/\/localhost\/test\/mm.png","name":"fm960","time":"8:00-12:00","ip":"http:\/\/192.168.3.99\/mp3\/m.mp3"}]}}

?

解析如下:

// 获取初始化mms列表
	public ArrayList<MmsModel> getModelList(String data) {
		ArrayList<MmsModel> al = new ArrayList<MmsModel>();
		try {
			JSONObject jm = new JSONObject(data).getJSONObject("audio");
			JSONArray jsonArray = jm.getJSONArray("info");
			for (int i = 0; i < jsonArray.length(); i++) {
				MmsModel am = new MmsModel();
				JSONObject jb = (JSONObject) jsonArray.opt(i);
				am.setId(jb.getString(MmsModel.ID));
				am.setName(jb.getString(MmsModel.NAME));
				am.setUrl(jb.getString(MmsModel.URL));
				al.add(am);
			}
			return al;
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("format json:", "false");
		}
		return null;
	}

?

2. 第二种格式是对象数组的json格式:

[{"id":"1","name":"liu"},{"id":"2","name":"kai"},{"id":"3","name":"lis"},{"id":"4","name":"you"}]

?解析如下:

public static ArrayList<TrafficModel> json4traffic(String data)
	{
		ArrayList<TrafficModel> al = new ArrayList<TrafficModel>();
		try {
			JSONArray jna = new JSONArray(data);
			for(int i=0; i<jna.length(); i++) 
			{
				TrafficModel tm = new TrafficModel();
				JSONObject jb = (JSONObject) jna.opt(i);
				tm.setId(jb.getString(TrafficModel.ID));
				tm.setName(jb.getString(TrafficModel.NAME));
				al.add(tm);
				//System.out.println("info is ------> : "+jb.getString(TrafficModel.URL));
			}
			return al;
		} catch(Exception e) {
			e.printStackTrace();			
		}		
		return al;
	}
?