【发布时间】:2013-07-24 09:34:35
【问题描述】:
在我的应用程序中,我试图从 facebook 获取最喜欢的音乐、电影、朋友的书籍。 到目前为止,我做到了。
- 我正在向 facebook 请求收藏夹并以 json 格式获取响应。
- 现在我想在后台解析它。
我的问题是解析执行速度很慢。我正在使用 for 循环进行迭代。整个解析需要 8 到 10 秒。所以有什么办法可以更快一点。
public ArrayList<String> parsing()
{
long time1=System.currentTimeMillis();
// System.out.println(time1);
ArrayList<String> urls=new ArrayList<String>();
int position=0;
try {
String response=Utility.responseSecond;
JSONObject node1=new JSONObject(response);
JSONArray array1=node1.getJSONArray("data");
int length=array1.length();
for(int i=0;i<length;i++)
{
if(array1.getJSONObject(i).getString("id").equals(friendId.toString()))
{
position=i;
}
}
JSONObject node2 = array1.getJSONObject(position);
try{
if(node2.has("music"))
{
JSONArray array2=node2.getJSONObject("music").getJSONArray("data");
JSONObject node4=array2.getJSONObject(0);
String name=node4.getString("name");
JSONObject node5=node4.getJSONObject("picture");
JSONObject node6=node5.getJSONObject("data");
String musicsurl=node6.getString("url");
urls.add(musicsurl);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
try{
if(node2.has("movies"))
{
JSONArray array2=node2.getJSONObject("movies").getJSONArray("data");
JSONObject node4=array2.getJSONObject(0);
String name=node4.getString("name");
JSONObject node5=node4.getJSONObject("picture");
JSONObject node6=node5.getJSONObject("data");
String moviesurl=node6.getString("url");
urls.add(moviesurl);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
try{
if(node2.has("books"))
{
JSONArray array2=node2.getJSONObject("books").getJSONArray("data");
JSONObject node4=array2.getJSONObject(0);
String name=node4.getString("name");
JSONObject node5=node4.getJSONObject("picture");
JSONObject node6=node5.getJSONObject("data");
String bookurl=node6.getString("url");
urls.add(bookurl);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
try{
if(node2.has("television"))
{
JSONArray array2=node2.getJSONObject("television").getJSONArray("data");
JSONObject node4=array2.getJSONObject(0);
String name=node4.getString("name");
JSONObject node5=node4.getJSONObject("picture");
JSONObject node6=node5.getJSONObject("data");
String televisionsurl=node6.getString("url");
urls.add(televisionsurl);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
} catch (Exception e) {
Log.i("JSONException", e.getMessage());
}
System.out.println("in parsing"+(System.currentTimeMillis()-time1));
return urls;
}
【问题讨论】:
-
你用过 Asyctask 吗?
-
是的,我正在使用异步任务。
-
我从doin后台调用这个方法并在onpostExecute方法中更新。
-
我认为你的数据是巨大的,如果可能的话在服务器端使用分页
-
与其自己解析json响应,不如花点时间学习jackson json parser wiki.fasterxml.com/JacksonHome。我已经用过很多次了,它的速度非常快,而且使用起来非常简单。也非常强大(和聪明)
标签: android json facebook-graph-api android-asynctask