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*
}
Both of the JSON examples you show are valid JSON, it’s just a matter of what your mapping is on each end.
Your java code is expecting “sample” to contain a collection (list or array) of objects where each object has a txt field. That’s why it has the [] around the object value in the JSON.
You can change the mapping on the java side to expect only a single value for sample, or you can change the php code so $data[‘sample’] is an array with a single element that has ‘txt’ = “hello world”.
If you include the mapping on the java side I can help with that. I’m sure some php guru could help if you want to fix it on the php side.
Edit:
JSONArray JSONarr=JSONobj.getJSONArray("sample");is asking for an array. Change that to a JSONObject and you should be good to go.