将JSONObject转换为字符串

时间:2013-07-12 06:53:54

标签: android

我想从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');

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

1 个答案:

答案 0 :(得分:2)

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

要么使用obj.getInt(“成功”)来获取它,要么将你的回报改为更像这样的东西;

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

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

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

对于Android中的上述JSON字符串,请创建一个包含Integer idString message的对象成功。

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

Success mSuccess = gson.fromJson(jsonString, Success.class);
相关问题