您的位置:首页 > 移动开发 > Android开发

android json与xml解析 例子

2012-03-15 17:43 513 查看
啥也不说了直接贴代码呃。

JSON解析:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.wasay.android.client.model.HomeMsg;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.util.Log;

public class JsonParser {
/**
* 通过URL从服务器上下载下来,保存为字符串,以便待会进行JSON解析
* @param strUrl
* @return
*/
public static String connServerForResult(String strUrl) {
// HttpGet对象
HttpGet httpRequest = new HttpGet(strUrl);
String strResult = "";
try {
// HttpClient对象
HttpClient httpClient = new DefaultHttpClient();

// 获得HttpResponse对象
HttpResponse httpResponse = httpClient.execute(httpRequest);
// 当返回码为200时,做处理  得到服务器端返回json数据,并做处理
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的数据
strResult = EntityUtils.toString(httpResponse.getEntity());
//				System.out.println(strResult);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strResult;
}

/**
* 普通Json数据解析  (这只是测试类,根据下载的JSON格式进行变化)
* @param strResult 从URL中得到的字符串
*/
public static void parseJson(String strResult) {
try {
JSONObject jsonObj = new JSONObject(strResult)
.getJSONObject("singer");
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String gender = jsonObj.getString("gender");
Log.e("Test", id + "," + name + ";" + gender);
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
}

/**
* blogs列表JSON转换
* 带数组的JSON数据转换
* @param strResult 从URL中转换过来的字符串
*/
// 要转换的格式如下
{"status":0,"result":[{"guid":"1278","owner_guid":"35","time":"2012-03-11 14:27:33","title":"1111",
// "description":"11111","subtype":"blog","entityurl":"http:\/\/wasay2.sinaapp.com\/blog\/view\/1278","name":"admin","userurl":"http:\/\/wasay2.sinaapp.com\/profile\/admin"}}
public static List<HomeMsg> parseJsons(String strResult) {
List<HomeMsg> blogs = new ArrayList<HomeMsg>();
try {
JSONTokener tokener = new JSONTokener(strResult);
JSONObject j = (JSONObject)tokener.nextValue();
int status = j.getInt("status");
JSONArray jsonObjs = j.getJSONArray("result");

if (0 == status) { // 0:正常返回; -1:出错
for (int i = 0; i < jsonObjs.length(); i++) {
// 封装数据
HomeMsg blog = new HomeMsg();
JSONObject jsonObj = ((JSONObject) jsonObjs.opt(i));
blog.setGuid(jsonObj.getInt("guid"));
blog.setOwnerGuid(jsonObj.getInt("owner_guid"));
blog.setTime(jsonObj.getString("time"));
blog.setTitle(jsonObj.getString("title"));
blog.setDescription(jsonObj.getString("description"));
blog.setSubType(jsonObj.getString("subtype"));
blog.setEntityUrl(jsonObj.getString("entityurl"));
blog.setName(jsonObj.getString("name"));
blog.setUserUrl(jsonObj.getString("userurl"));
blogs.add(blog);
}
}
} catch (JSONException e) {
System.out.println("Jsons parse error !");
e.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
return blogs;
}
}

XML解析 DOM:

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlDomParser {
/**
*  解析XML文档
* @param fileName 文件全路径名称
*/
public static void parserXml(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(fileName);
NodeList employees = document.getChildNodes();
for (int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
NodeList employeeInfo = employee.getChildNodes();
for (int j = 0; j < employeeInfo.getLength(); j++) {
Node node = employeeInfo.item(j);
NodeList employeeMeta = node.getChildNodes();
for (int k = 0; k < employeeMeta.getLength(); k++) {
if (!"#text".equals(employeeMeta.item(k).getNodeName())) {
System.out.println(employeeMeta.item(k).getNodeName()
+ ":" + (employeeMeta.item(k)).getTextContent());
}
}
}
}
System.out.println("解析完毕");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}


XMl SAX 解析 :

package net.wasay.android.client.parser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
* 优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。
* 缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了;无状态性;从事件中只能得到文本,
* 但不知该文本属于哪个元素;
* 使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少;
* @author wangbin
* SAX文档解析
*/

public class XmlSaxParser {
/**
*  解析XML文档
* @param fileName 文件全路径名称
*
*/
public static void parserXml(String fileName) {
SAXParserFactory saxfac = SAXParserFactory.newInstance();
try {
SAXParser saxparser = saxfac.newSAXParser();
InputStream is = new FileInputStream(fileName);
saxparser.parse(is, new MySAXHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

class MySAXHandler extends DefaultHandler {
boolean hasAttribute = false;
Attributes attributes = null;

public void startDocument() throws SAXException {
System.out.println("startDocument");
}

public void endDocument() throws SAXException {
System.out.println("endDocument");
}

public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("employees")) {
return;
}
if (qName.equals("employee")) {
System.out.println(qName);
}
if (attributes.getLength() > 0) {
this.attributes = attributes;
this.hasAttribute = true;
}
}

public void endElement(String uri, String localName, String qName)
throws SAXException {
if (hasAttribute && (attributes != null)) {
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println(attributes.getQName(0)
+ attributes.getValue(0));
}
}
}

public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println(new String(ch, start, length));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: