doutuo1939 2012-03-30 04:24
浏览 72

Android中的JSON异常

I am trying to execute query on database in the localhost and send the JSON object to the client in android. I m not been able to know what is the problem in my code. So some one please help me on this regard.

My php code is the one where i m sending the JSON object. php code

query executed successfully..

$row=mysql_fetch_array($result1);


    $email=$row['EM'];
    $pass=$row['PASS'];

    $post=array("email"=>$email, "pass"=>$pass); 
    $posts[] = array("post"=>$post);
    //echo "SUCCESS";
    header('Content-type: application/json');

    echo json_encode(array("posts"=>$posts));

And in android side i ve this code below;

HttpResponse response = doPost(url, kvPairs);
        String responseBody=response.toString();
        String temp = EntityUtils.toString(response.getEntity());
        if (temp.compareTo("SUCCESS")==0)
        {
            Toast.makeText(this, "Working", Toast.LENGTH_LONG).show();
        }

Above part executes .. Below code throws a JSON exception

        JSONObject json = new JSONObject(responseBody);
    JSONArray jArray = json.getJSONArray("posts");
    no_of_obj=jArray.length();
    nemail=new String[no_of_obj];
    npass=new String[no_of_obj];
    for (int i = 0; i < jArray.length(); i++) {
        JSONObject e = jArray.getJSONObject(i);
        String s = e.getString("post");
        JSONObject jObject = new JSONObject(s);
       Toast.makeText(context,jObject.getString("email")+":"+jObject.getString("pass") , duration).show();
        nemail[i]=jObject.getString("email");
        npass[i]=jObject.getString("pass");

    }

In the log cat i can see : The json string must begin with "{"....

  • 写回答

2条回答 默认 最新

  • douhun8647 2012-03-30 04:32
    关注

    Probably you cannot do this

    String s = e.getString("post");
    

    because there is no "post" key in the array of Strings you have given,...

    Try doing this,

    String s = e.has("post")?e.getString("post"):null;
    

    and then on next line keep a null check before Creating JSONObject..

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源