-1

我有我想从 Android 获取的 JSON 数据

{"success":1,"message":"Product successfully created."}

完整代码在这里:

<?php
header('Content-type: application/json');
mysql_connect("127.0.0.1","root","");
mysql_select_db("android");
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$username=$_POST['username'];
$password=$_POST['password'];
$sql=mysql_query("select * from info  ");
if($sql)
{
    $response["success"] = 1
    $response["message"] = "Product successfully created.";
    echo json_encode($response);
}
else
{
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    $data[]=$response;
    // echoing JSON response
    echo json_encode($response);
    echo json_encode($data);
}
while($row=mysql_fetch_array($sql)) 
    $output[]=$row;
json_encode($output);
print(json_encode($output));
mysql_close();
?>

我到底想要做的是得到响应是否成功或失败其余的工作,例如从数据库中检索数据。

我试过这段代码:

JSONObject obj=new JSONObject(sb.toString())

然后

JSONObject objdata=obj.getJSONObject('success');

但出现“类型不匹配”和“无法转换”等错误

4

1 回答 1

2

正如@Shaiful 所说,成功不是一个对象。

要么,使用 obj.getInt("success") 来获取它,要么将您的回报更改为更像这样的东西;

{
   "success":{
      "id":1,
      "message":"Product successfully created."
   }
}

如果您只是在 PHP 中编写更多面向对象的程序而不是转换数组,那么这会更自动,因为 json_encode(); 如果你给它一个对象,它也会为你创建一个适当的 json 字符串。

编辑:您应该结合JSON 及其语法查找类型(对象、数组、整数、字符串...)。看你的评论,你并没有得到很多。

对于 Android 中的上述 JSON 字符串,使用 anInteger id和 a创建一个 Success 对象String message

然后使用该Gson库自动提取它:

Success mSuccess = gson.fromJson(jsonString, Success.class);
于 2013-07-12T07:10:57.750 回答