title: JSON encoding data for Android app
body: <p>I'm trying to send JSON data from a php script to an Android app and the php script's output is different from what the Java app expects.</p>
  
  <pre><code>$data['sample']['txt']="hello world";
  echo json_encode($data) // {"sample":{"txt":"hello world"}}
  //above is incorrect, need {sample : [{txt:"hello world"}]}
  </code></pre>
  
  <p>The incorrect format results in the following Java exception: </p>
  
  <pre><code>org.json.JSONException: Value {"txt":"hello world"} at sample of type org.json.JSONObject cannot be converted to JSONArray.  
  </code></pre>
  
  <p>Is there an argument of PHP's json_encode that I'm missing, or an alternative that would encode it properly?</p>
  
  <p>Java code for async task:</p>
  
  <pre><code>public class RetrieveData extends AsyncTask&lt;List&lt;? extends NameValuePair&gt;, Integer, List&lt;String&gt;&gt; {
  
      protected List&lt;String&gt; doInBackground(List&lt;? extends NameValuePair&gt;... postData) {
          InputStream is = null;
          List&lt;String&gt; result = new ArrayList&lt;String&gt;();
  
          try {
              HttpClient httpclient = new DefaultHttpClient();
              HttpPost httppost = new HttpPost("http://192.168.72.2:10088/droid_test/test.php");
              httppost.setEntity(new UrlEncodedFormEntity(postData[0]));
              HttpResponse response = httpclient.execute(httppost);
              HttpEntity entity = response.getEntity();
              is = entity.getContent();
  
              BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");
              }
              reader.close();
              is.close();
  
              JSONObject JSONobj=new JSONObject(sb.toString());
              JSONArray JSONarr=JSONobj.getJSONArray("sample");
  
              for(int i = 0 ; i &lt; JSONarr.length() ; i++){
                  result.add(JSONarr.getJSONObject(i).getString("txt"));
              }
  
              }
          catch(Exception e) {
              result.add("ERROR "+e.toString());
          }
  
          return result;
      }
  
      protected void onPostExecute(List&lt;String&gt; result) {
              getHTTP(result);
      }
  
  }
  </code></pre>
  
  <p>getHTTP(result) just sets the value to a TextView, which is where the error is displaying. (or the response if I hard code the echo statement)</p>
  
  <p>Solution:</p>
  
  <pre><code>JSONObject JSONobj=new JSONObject(sb.toString());
  JSONObject JSONarr=JSONobj.getJSONObject("sample"); // made object per @digitaljoel's suggestion
  
  for(int i=0; i&lt;JSONarr.length(); i++) {
      result.add(JSONarr.getString("txt")); // getting a String, not another array/object *duh*
  }
  </code></pre>