就目前来讲,在 Android 开发中,还是以 JSON 格式数据较为常见,但偶尔还是会碰到需要在项目中使用 XML 格式数据的情况,这篇文章总结了几种常见的解析 XML 和 JSON 数据的用法
XML解析
<apps>
<app>
<id>111</id>
<city>江西</city>
<weather>阴转晴</weather>
</app>
<app>
<id>222</id>
<city>湖南</city>
<weather>雨夹雪</weather>
</app>
</apps>
Pull解析XML
private void parseXMLWithPull(String xmlData) {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser pullParser = factory.newPullParser();
pullParser.setInput(new StringReader(result));
int eventType = pullParser.getEventType();
final StringBuilder sb = new StringBuilder();
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = pullParser.getName();
switch (eventType) {
case XmlPullParser.START_TAG: {
if ("id".equals(nodeName)) {
sb.append(pullParser.nextText());
} else if ("city".equals(nodeName)) {
sb.append(pullParser.nextText());
} else if ("weather".equals(nodeName)) {
sb.append(pullParser.nextText());
sb.append("\n");
}
break;
}
case XmlPullParser.END_TAG:{
if ("app".equals(nodeName)) {
runOnUiThread(new Runnable() {
mTextView.setText(sb.toString());//在主线程中更新UI
}
});
}
break;
}
default:
break;
}
eventType = pullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
SAX解析XML
private void parseXMLWithSAX(String xmlData) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
//通过获取到的InputStream来得到InputSource实例
InputSource inputSource = new InputSource(new StringReader(xmlData));
//初始化自定义的类MyXMLParserHandler,将mList传递给它,以便装载数据
xmlReader.setContentHandler(new MyXMLParserHandler(mList));//之前要定义并初始化
xmlReader.parse(inputSource);
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
自定义MyXMLParserHandler类(BeanItem对象用来装载值)
public class MyXMLParserHandler extends DefaultHandler {
//声明一个字符串变量
private String content;
//声明一个装载Beauty类型的List
private List<BeanItem> mList;
private BeanItem beanItem;
public MyXMLParserHandler(List<BeanItem> mList) {
this.mList = mList;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
//开始解析某个节点
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if ("app".equals(localName)) {
beanItem = new BeanItem();
}
}
//当SAX解析器解析到某个属性值时,会调用的方法,其中参数ch记录了这个属性值的内容
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
content = new String(ch,start,length);
}
//当SAX解析器解析到某个元素结束时,会调用的方法,其中localName记录的是元素属性名
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if ("id".equals(localName)) {
beanItem.setId(content);
} else if ("city".equals(localName)) {
beanItem.setCity(content);
} else if ("weather".equals(localName)) {
beanItem.setWeather(content);
} else if ("app".equals(localName)) {
mList.add(beanItem);
}
}
//完成整个XML解析时调用
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
DOM解析XML(Android不推荐)
解析JSON数据
[
{"id":"5","version":"5.5","name":"Angry Birds"},
{"id":"6","version":"7.0","name":"Clash of Clans"},
{"id":"7","version":"3.5","name":"Hey Day"}
]
- JSONObject解析
private void parseJSONWithJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObject.getString("version");
}
} catch (Exception e) {
e.printStackTrace();
}
}
- GSON解析
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
List<ItemBean> itemList = gson.fromJson(jsonData, newTypeToken<List<ItemBean>>() {}.getType());//ItemBean是吧JSON数据的id,version,name封装成了一个对象
for (ItemBean item : itemList) {
Log.d("MainActivity", "id is " + item.getId());
Log.d("MainActivity", "name is " + item.getName());
Log.d("MainActivity", "version is " + item.getVersion());
}
}
border="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=5307982&auto=1&height=66">