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.
$data['sample']['txt']="hello world";
echo json_encode($data) // {"sample":{"txt":"hello world"}}
//above is incorrect, need {sample : [{txt:"hello world"}]}
The incorrect format results in the following Java exception:
org.json.JSONException: Value {"txt":"hello world"} at sample of type org.json.JSONObject cannot be converted to JSONArray.
Is there an argument of PHP's json_encode that I'm missing, or an alternative that would encode it properly?
Java code for async task:
public class RetrieveData extends AsyncTask<List<? extends NameValuePair>, Integer, List<String>> {
protected List<String> doInBackground(List<? extends NameValuePair>... postData) {
InputStream is = null;
List<String> result = new ArrayList<String>();
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 < JSONarr.length() ; i++){
result.add(JSONarr.getJSONObject(i).getString("txt"));
}
}
catch(Exception e) {
result.add("ERROR "+e.toString());
}
return result;
}
protected void onPostExecute(List<String> result) {
getHTTP(result);
}
}
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)
Solution:
JSONObject JSONobj=new JSONObject(sb.toString());
JSONObject JSONarr=JSONobj.getJSONObject("sample"); // made object per @digitaljoel's suggestion
for(int i=0; i<JSONarr.length(); i++) {
result.add(JSONarr.getString("txt")); // getting a String, not another array/object *duh*
}