I wrote a simpe PHP script that prints an jsonencode($output). It outputs the JSON with a leading and ending []. When I run my Android program through the emulaotor, it states: A JSONObject text must begin with ‘{‘ at character 1 of [….. then lists my JSON, so I know its getting the data, there is a problem with the decode process that its not removing those square brackets. Here is the function that is throwing the error to the log:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
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");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
It sounds like your JSon response looks like:
[{'name':'value'},...]Your JSon Object must begin with
{like the error message says. It should be:{'my_array':[.......]}Then you could write:
new JSONObject().getJSONArray("my_array");