繁体   English   中英

尝试将带有JSON的PHP数据返回到Android ...

[英]Trying to return data from PHP with JSON to Android…

尝试将带有JSON的PHP数据返回到Android。 下面是我的PHP脚本

<?php 
#
print(json_encode("[name=john]"));
#
?>

但是我在java中收到错误:ERROR / log_tag(907):解析数据时出错org.json.JSONException:JSONArray文本必须以'['在字符0处开头

json_encode需要一个实际的对象或数组来编码为json格式。 此外,最好为响应标头设置内容类型。 试试这个:

<?php
    header('Content-type: application/json');
    print json_encode(array('name' => 'john'));
?>

我不太了解java方面。 正如nikc所提到的, json_encode将关联数组更改为json对象,将数值数组更改为json数组。

你用json_encode编码一个json数组。 在json [](方括号)中代表对象的数组和{}(curley括号)。 使用[enobrev]给出的样本,返回一个json对象而不是json数组。

在这种情况下你的解决方案将在android中调用

//Example of the content of result:
// {"name":"john"} This would be the result returned from the restfull request
// This the above JSON would be stored in a variable of type String.
JSONObject obj = new JSONObject(result); //JSONObject's constructor accepts a string as parameter

当你有了对象时,你可以写:

obj.getString("name");

这将检索密钥为“name”的值

它的用法示例可以是:

Toast.makeText(context, obj.getString("name"), Toast.LENGTH_LONG).show();

返回约翰。

因为你得到的错误意味着你试图用json对象创建一个json数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM