Android解码json响应

时间:2010-10-15 06:35:01

标签: android exception json

请求处理代码

  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”],[ “柄”, “25”, “division1”],[ “Aatmaj”, “54”, “division1” ],[ “阿沛”, “46”, “division2”],[ “Bhinatha”, “37”, “division2”],[ “Abhineet”, “29”, “division3”],[ “Srita”,” 47" , “division1”]]

Android代码

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();
    }

导致异常

  

org.json.JSONException:一个JSONObject   文本必须以字符1中的“{”开头   的   [[ “Aadidev”, “23”, “division1”],[ “Ragman”, “35”, “division3”],[ “Sahlaad”, “27”, “division1”],[ “Maraadhak”,“21 ”, “division2”],[ “的Arya”, “48”, “division1”],[ “柄”, “25”, “division1”],[ “Aatmaj”, “54”, “division1”],[ “阿沛”, “46”, “division2”],[ “Bhinatha”, “37”, “division2”],[ “Abhineet”, “29”, “division3”],[ “Srita”, “47”, “division1”]]。

3 个答案:

答案 0 :(得分:1)

您可以使用echo json_encode($data, JSON_FORCE_OBJECT);强制创建对象。

在数组上使用json_encode()不会生成Java JSONObject似乎假设的对象。

这是PHP&gt; = 5.3!

答案 1 :(得分:0)

你的json字符串应该以'{'字符开头。尝试从php应用程序中解析字符串,看看会发生什么。

答案 2 :(得分:0)

尝试更改您的PHP代码:

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);



这将返回一个json字符串,如:
[{ “Name”: “名1”, “年龄”: “AGE-1”, “部门”: “DEPT1”},{ “名”: “NAME2”, “年龄”: “AGE2岁”, “部门”:“DEPT2 “}]



然后你需要在java代码中解析这个json字符串