解析xml和json[转]

http://www.cnblogs.com/Ashia/archive/2012/03/09/2386073.html

 

今天彻底被 json 伤到了

 

03-08 13:45:44.648: W/System.err(14432): org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray

 

该异常有 json 文件编码所引起的,所以切切不要应用 记事本 编辑 json 文件,而应选择其他文本编辑器,如 EditPlus ,并重视保存编码格局为 UTF-8,不然可能产生中文乱码。

 

用记事本编辑后,即使 另存为 UTF-8 情势,也会产生乱码,因为保存在为 UTF-8 + BOM 编码

 

因为我是将 json 文件放在 tomcat ,进行读取的。从而导致该题目产生。

 

 

 


public class BlogService {

// 解析 json
public List<Blog> getBlogsByJSON() throws Exception {
URL url = new URL("http://192.168.1.111:8080/examples/json.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);

List<Blog> blogs = null;

if (conn.getResponseCode() == 200) {
byte[] data = LoadUtil.load(conn.getInputStream());
String json = new String(data);
JSONArray array = new JSONArray(json);

blogs = new ArrayList<Blog>();
Blog blog = null;

for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
blog = new Blog(obj.getInt("id"), obj.getString("protraint"), obj.getString("name"), obj.getString("content"), obj.getString("picture"));
blogs.add(blog);
}
}
return blogs;
}

// 解析 xml
public List<Blog> getBlogs() throws Exception {
URL url = new URL("http://192.168.1.254:8080/14.Web/blog.xml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);

if (conn.getResponseCode() == 200) {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(conn.getInputStream(), "UTF-8");

List<Blog> blogs = null;
Blog blog = null;

for (int event = parser.getEventType(); event != XmlPullParser.END_DOCUMENT; event = parser.next())
if (event == XmlPullParser.START_TAG) {
if ("blogs".equals(parser.getName()))
blogs = new ArrayList<Blog>();
if ("blog".equals(parser.getName())) {
blog = new Blog();
blog.setId(Integer.parseInt(parser.getAttributeValue(0)));
blogs.add(blog);
}
if ("protraint".equals(parser.getName()))
blog.setProtraint(parser.nextText());
if ("username".equals(parser.getName()))
blog.setUsername(parser.nextText());
if ("content".equals(parser.getName()))
blog.setContent(parser.nextText());
if ("picture".equals(parser.getName()))
blog.setPicture(parser.nextText());
}
return blogs;
}

throw new NetworkErrorException("接见收集异常");
}

}
posted @ 2012-05-22 11:21  aflylove  阅读(301)  评论(0编辑  收藏  举报