android中常见的二种数据解析方法----XML和Json

第一种:XML解析:

String xmlStr = "1google2ie3chrome";
	
	public void parseXMLWrithPull(String xmlStr) {
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
			XmlPullParser xmlPullParser = factory.newPullParser();
			xmlPullParser.setInput(new StringReader(xmlStr));
			int eventType = xmlPullParser.getEventType();
			String id = "";
			String name = "";
			while(eventType != XmlPullParser.END_DOCUMENT) {
				String nodeName = xmlPullParser.getName();
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if("id".equals(nodeName)) {
						id = xmlPullParser.nextText();
					} else if("name".equals(nodeName)) {
						name = xmlPullParser.nextText();
					}
					break;
					
				case XmlPullParser.END_TAG:
					if("app".equals(nodeName)) {
						Log.i("id=", id);
						Log.i("name=", name);
					}
					break;

				default:
					break;
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

第二种:Json数据解析:

(一) JsonObject:

public void parseJsonWithJSONObject(String jsonData) {
		JSONArray jsonArray = new JSONArray();
		for(int i = 0; i

(二) GSON解析:

public Class App{
		private String id;
		private String name;

		public String getId() {
			return id;
		}		
		public void setId(String id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		
	}
	
	public void parseJsonwithGSON(String jsonData) {
		Gson gson = new Gson(); 
		List applist = gson.fromJson(jsonData, new TypeToken>(){}.getType());
		for(App app : appList){
			Log.i("id", app.getId());
			Log.i("name", app.getName());
		}
		
	}

以上就是二种比较主流的解析方法。


你可能感兴趣的:(Android,Android,学习笔记)