将JSONObject转换为字符串

冰冷的理查兹

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

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

斯蒂芬·德·布赖恩(Stefan de Bruijn)

正如@Shaiful所说,成功不是目标。

要么使用obj.getInt(“ success”)来获取它,要么将您的收益改成类似这样的东西;

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

如果您只是简单地在PHP中编写更多面向对象的程序,而不是转换数组,则这样做会更自动,因为json_encode(); 如果给它一个对象,也会为您创建一个正确的json字符串。

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

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

然后使用该Gson库自动将其提取为:

Success mSuccess = gson.fromJson(jsonString, Success.class);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章