Improve JSON parsing
authorMarius Gavrilescu <marius@ieval.ro>
Tue, 12 Mar 2013 08:56:52 +0000 (10:56 +0200)
committerMarius Gavrilescu <marius@ieval.ro>
Tue, 12 Mar 2013 08:56:52 +0000 (10:56 +0200)
Command arguments are now represented as JSON arrays, and the
JSON parsing code uses less memory. Previous versions can no
longer receive commands, since they expect command arguments in
the old arg0, arg1, ... form.

src/ro/ieval/fonbot/PollServerAsyncTask.java

index 1be09c36a1730857fc4c1749daf2127090ae5f51..07c014b0979c9245e17aa1f83b71b5917c6c9cdf 100644 (file)
@@ -109,24 +109,29 @@ public final class PollServerAsyncTask extends AsyncTask<Void, Void, List<PollSe
                        conn.setRequestProperty("Authorization", "Basic "+Base64.encodeToString(
                                        (user+':'+password).getBytes(), Base64.NO_WRAP));
                        conn.connect();
-                       final byte[] buf=new byte[4096*1024];
                        Log.d(getClass().getName(), "Server poll got response code "+conn.getResponseCode()+" and message "+conn.getResponseMessage());
                        if(conn.getResponseCode()!=200)
                                return commands;
-                       conn.getInputStream().read(buf);
-                       final JSONArray array=new JSONArray(new String(buf));
-                       final List<String> list=new ArrayList<String>();
+
+                       final JSONArray array;
+                       {
+                               final byte[] buf=new byte[4096*1024];
+                               conn.getInputStream().read(buf);
+                               array=new JSONArray(new String(buf));
+                       }
+
                        for(int i=0;i<array.length();i++){
                                final JSONObject object=array.getJSONObject(i);
 
-                               for(int j=0;object.has("arg"+j);j++)
-                                       list.add(object.getString("arg"+j));
+                               final JSONArray jsonargs=object.getJSONArray("args");
+                               final String[] args=new String[jsonargs.length()];
+                               for(int j=0;j<args.length;j++)
+                                       args[j]=jsonargs.getString(j);
 
                                commands.add(new Command(//NOPMD command changes for each JSON object
                                                toNonNull(object.getString("command")),
-                                               toNonNull(list.toArray(new String[list.size()])),
+                                               args,
                                                toNonNull(object.getString("replyto"))));
-                               list.clear();
                        }
                } catch (MalformedURLException e) {
                        e.printStackTrace();
This page took 0.010633 seconds and 4 git commands to generate.