【发布时间】:2016-09-01 14:00:46
【问题描述】:
我有一个从 JSON URL 加载数据的应用,但加载大约需要 8 秒,我相信这是因为解析。
我想知道是否有更快更简单的解析方法?
这是我用来读取 JSON 的函数:
public class LoadJson extends AsyncTask <String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
return finalJson;
} catch (Exception e) {
e.printStackTrace();
return "Faild";
}
}
}
和:
public JSONArray ExcuteLoad() {
LoadJson task = new LoadJson();
String resualt = null;
try {
resualt = task.execute("MY_JSON_FILE_URL").get();
JSONObject json = new JSONObject(resualt);
JSONArray jarray = json.getJSONArray("marcadores");
return jarray;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
更新 1:
好吧,伙计们,我根据您对使用 onPostExecute 的建议更改了代码,但问题是我无法在 asyncTask 之外返回 jsonarray 的值,真的很困惑....
public class LoadJson extends AsyncTask <String, Void, String> {
public class LoadJson extends AsyncTask <String, Void, String> {
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public LoadJson (AsyncResponse delegate){
this.delegate = delegate;
}
@Override
protected String doInBackground(String... params) {
String resualt = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
resualt += current;
data = reader.read();
}
return resualt;
}
catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
@Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
和我的片段类:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
LoadJson asyncTask = (LoadJson) new LoadJson (new LoadJson.AsyncResponse(){
@Override
public void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
try {
JSONObject jsonObject = new JSONObject(output);
JSONArray jsonArray = jsonObject.getJSONArray("marcadores");
} catch (JSONException e) {
e.printStackTrace();
}
}
}).execute();
【问题讨论】:
-
除了你正在做的奇怪的解析之外,你还有一个与
task.execute().get()同步的任务 -
您可以使用 Jackson 来解析 Json,因为它速度很快,而且大多数供应商都使用 Jakson 来解析 JSON,即。 DropBox,Box.....仅供参考:blog.takipi.com/…
-
我相信这是因为解析 - 您认为这是解析器,但您不确定。检测您的代码并找出问题所在!
-
@MuratK。你相信如果我把它改成在 1 个函数中工作,它会工作得更快吗?