Home  >  Article  >  Backend Development  >  ios - PHP传给app的JSON有什么要求?

ios - PHP传给app的JSON有什么要求?

WBOY
WBOYOriginal
2016-06-06 20:27:471174browse

我从数据库取出数据后发到web上,让APP去获取信息:

<code>$result = mysql_query("select * from his");
while ($arr = mysql_fetch_assoc($result)) {
    $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
    echo $json;
}</code>

输出到界面的json为:
{"hps_userid":"1","hps_userid2":"1"}
现在app端无法获取数据是我的输出格式问题还是app那边的问题?

现在app那边的同事说需要这种格式才可以

{"No.":[{"hps_userid":"1","hps_userid2":"1"}]}

当搜索到多条数据的时候,又要怎么如何输出?

回复内容:

我从数据库取出数据后发到web上,让APP去获取信息:

<code>$result = mysql_query("select * from his");
while ($arr = mysql_fetch_assoc($result)) {
    $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
    echo $json;
}</code>

输出到界面的json为:
{"hps_userid":"1","hps_userid2":"1"}
现在app端无法获取数据是我的输出格式问题还是app那边的问题?

现在app那边的同事说需要这种格式才可以

{"No.":[{"hps_userid":"1","hps_userid2":"1"}]}

当搜索到多条数据的时候,又要怎么如何输出?

“现在app那边的同事说需要这种格式才可以”,“才可以”,哈哈。。。
以前我和别人合作的时候也听到过类似的说法,然而后来我学了安卓开发。。。
妈蛋的,才发现,明明是他们解析JSON的代码不怎么会写,还怪我给的格式不对。。。

只要输出的是标准的JSON格式,信息完整,组织正确,根本不存在解析不了的问题。

<code>{"No.":[{"hps_userid":"1","hps_userid2":"1"}]}
</code>

这个"No"的存在并没有什么必要(只是因为他们JSON解析不太会)。
话说,“当搜索到多条数据的时候,又要怎么如何输出?"
这种问题应该一开始就考虑好,好吧?

<code>[
    {
        "hps_userid": "1",
        "hps_userid2": "1"
    },
    {
        "hps_userid": "2",
        "hps_userid2": "3"
    },
    {
        "hps_userid": "4",
        "hps_userid2": "5"
    }
]
</code>

取多条数据,最后都保存到一个数组里,然后把数组转成JSON,就是上面这样的了。
话说你的代码怎么会是这样。。。

<code>$result = mysql_query("select * from his");
while ($arr = mysql_fetch_assoc($result)) {
    $json = json_encode($arr,JSON_UNESCAPED_UNICODE);
    echo $json;
}
</code>

你知道while循环了几次吗?每次循环都echo,最后输出的是类似这样的:

<code>{"hps_userid":"1","hps_userid2":"1"}{"hps_userid":"1","hps_userid2":"1"}{"hps_userid":"1","hps_userid2":"1"}{"hps_userid":"1","hps_userid2":"1"}{"hps_userid":"1","hps_userid2":"1"}{"hps_userid":"1","hps_userid2":"1"}
</code>

这种连起来的就根本不是JSON字符串啊。。。
。。。。。。
如下:

<code>$result = mysql_query("select * from his");
$Temp = array();
$row = mysql_fetch_assoc($result);
while ($row) {
    $Temp[] = array("hps_userid"=>$row["hps_userid"],"hps_userid2"=>$row["hps_userid2"]);
    $row = mysql_fetch_assoc($result);
}
die(json_encode($Temp));
//或者你就听你们那个逗比APP工程师的:
//die(json_encode(array("No."=>$Temp)));
</code>

这里是需要循环的,所以你给你们逗比工程师的json,是需要用 [{xxx:1},{xxx:2}] 这种格式的

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn