views:

60

answers:

3

the request processing code

  while($op=db_fetch_object($result))
  {
    $data[$i++]=array($op->name,$op->age,$op->dept);
  }

  echo json_encode($data);

$data contains

[["Aadidev","23","division1"],["Ragman","35","division3"],["Sahlaad","27","division1"],["Maraadhak","21","division2"],["Arya","48","division1"],["Shank","25","division1"],["Aatmaj","54","division1"],["Abhay","46","division2"],["Bhinatha","37","division2"],["Abhineet","29","division3"],["Srita","47","division1"]]

Android code

String nameop="";
 try{
    JSONObject json=new JSONObject(page);
    JSONArray namearr=json.names();
    JSONArray valarr=json.toJSONArray(namearr);
    for(int i=0;i<valarr.length();i++)
    {
     nameop+=namearr.getString(i)+" "+valarr.getString(i)+"\n";
    }
    result.setText(nameop);
    }catch(Exception e){
     Toast.makeText(this,e.toString(), Toast.LENGTH_LONG).show();
    }

which results an exception

org.json.JSONException: A JSONObject text must begin with '{' at character 1 of [["Aadidev","23","division1"],["Ragman","35","division3"],["Sahlaad","27","division1"],["Maraadhak","21","division2"],["Arya","48","division1"],["Shank","25","division1"],["Aatmaj","54","division1"],["Abhay","46","division2"],["Bhinatha","37","division2"],["Abhineet","29","division3"],["Srita","47","division1"]].

A: 

Your json string should indeed begin with a '{' character. Try parsing the string from within your php app and see what happens.

Miguel Morales
A: 

Try changing your php code a bit:

while($op=mysql_fetch_array(mysql_query(your query)))
{
    $data[$i]["name"]= $op["name"];
    $data[$i]["age"]= $op["age"];
    $data[$i]["dept"]= $op["dept"];
    $i++;
}

echo json_encode($data);



This will return a json string like:
[{"name":"name1","age":"age1","dept":"dept1"},{"name":"name2","age":"age2","dept":"dept2"}]



Then you need to parse this json string in java code

viv
viv it gives same error
Paniyar
I have slightly changed the code above try it using this way........ also try what " Zoran Zaric " has told
viv
the java json parser seems to expect a "{" as the first character, so it won't accept "your" json string.
Zoran Zaric
This will create problem if we use JSONObject, JSONObject expects first character as "{". But my string is a type of an array of JSONObject, so in this case one will have to use JSONArray and loop through each object. Thanks..............
viv
+1  A: 

You can use echo json_encode($data, JSON_FORCE_OBJECT); to force creation of an object.

Just using json_encode() on an array doesn't generate an object, which Java's JSONObject seems to assume.

this is PHP >= 5.3!

Zoran Zaric