JSONVs XML
1.JSON和XML的数据可读性基本相同
2.JSON和XML同样拥有丰富的解析手段
3.JSON相对于XML来讲,数据的体积小
4.JSON与JavaScript的交互更加方便
5.JSON 对数据的描述性比 XML 较差
6.JSON 的速度要远远快于 XML
AndroidJSON解析
privateString weatherUrl="http://www.weather.com.cn/adat/cityinfo/101040500.html";
privatestaticString[] jsonStrings={"weatherinfo","city","cityid","temp1","temp2","weather","img1","img2","ptime"};
publicstaticvoidgetJsonObject(String restString, finalString[] jsonStrings, intnum) {
String[]restjson = newString[jsonStrings.length];
JSONObjectjsonObject = null;
intjsonDataLen = 1;
try{
for(inti = 0; i<num; i++){
jsonObject= newJSONObject(restString);//获取JSONObject对象
if(i== num-1)
continue;
restString= jsonObject.getString(jsonStrings[i]);//获取JSON解析的字符串数据
}
for(inti=num-1; i<jsonStrings.length;i++){
restString= jsonObject.getString(jsonStrings[i]);
restjson[jsonDataLen]= restString;
Log.d("look",jsonStrings[i]+"="+restjson[jsonDataLen]);
if(i== jsonStrings.length-1)
continue;
jsonDataLen++;
}
Log.d("look","jsonDataLen="+jsonDataLen);
}catch(JSONException e) {
e.printStackTrace();
}
Log.d(TGA,"ly++++++getJsonObject");
}
AndroidXML解析
privateString weatherUrl="http://api.k780.com:88/?app=weather.today&weaid=101280601&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=xml";
publicstaticvoidgetXmlPullParser(InputStream inputStream) {
//由android.util.Xml创建一个XmlPullParser实例
XmlPullParserxmlPullParser = Xml.newPullParser();
try{
//设置输入流并指明编码方式
xmlPullParser.setInput(inputStream,"UTF-8");
//产生第一个事件
inteventType = xmlPullParser.getEventType();
while(eventType!=XmlPullParser.END_DOCUMENT){
switch(eventType){
//判断当前事件是否为文档开始事件
caseXmlPullParser.START_DOCUMENT:
//可在这里进行一些初始化的事情
break;
//判断当前事件是否为标签元素开始事件
caseXmlPullParser.START_TAG:
//判断开始标签元素
if(xmlPullParser.getName().equals("result")){
} elseif(xmlPullParser.getName().equals("weaid")){
//标记指针向下移动一位后再得到weaid标签的属性值,记住每获得一次数据都得移动一次标记,
//当一个标记中有多个数据时用getAttributeValue(index)方法得到多个数据。
eventType = xmlPullParser.next();
String weaidString = xmlPullParser.getText();
Log.d("look","weaid"+weaidString);
} elseif(xmlPullParser.getName().equals("days")){
eventType = xmlPullParser.next();
String daysString = xmlPullParser.getText();
Log.d("look","days"+daysString);
} elseif(xmlPullParser.getName().equals("temperature")){
eventType = xmlPullParser.next();
String temperatureString = xmlPullParser.getText();
Log.d("look","temperature"+temperatureString);
} elseif(xmlPullParser.getName().equals("weather")){
eventType = xmlPullParser.next();
String weatherString = xmlPullParser.getText();
Log.d("look","weather"+weatherString);
}
break;
//判断当前事件是否为标签元素结束事件
caseXmlPullParser.END_TAG:
break;
}
//进入下一个元素并触发相应事件
eventType= xmlPullParser.next();
}
}catch(XmlPullParserException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
Log.d(TGA,"ly++++++getXmlPullParser");
}