【发布时间】:2015-06-11 04:37:59
【问题描述】:
在我的drupal 网站中,我使用drupal web 服务模块为android 和php 客户端提供api。这是我正确返回 json 格式的示例 api 链接 (http://localhost/myproject/api/v1/users/registered_users/retrieve.json),我还检查了 http://jsonlint.com/ 中返回的 json,表明我的 json 格式有效。
这里是从本地主机返回的 json...
{
"status": "1",
"mobile_user": [
{
"id": "1",
"name": "saa",
"phone_no": "09978784963",
"activate_code": "",
"deposit": "0",
"created": "2015-05-29 00:00:00",
"updated": "0000-00-00 00:00:00",
"status": "1"
}
]
}
json返回在android中运行良好,我可以调用webservice api,当解析json返回时,在android中一切正常,没有错误。但我无法解析 php 中的 json 返回,php 中最常用的 json 解码方法是 json_decode() 函数。当我使用 json_last_error() 检查 json 返回时,显示“语法错误,格式错误的 JSON”。如果你愿意,我必须更正我的代码。
谢谢,
这是我调用drupal webservice的php代码......
<?php
mb_internal_encoding('UTF-8');
$url = 'http://192.168.1.111/busexpress/api/v1/mobile_user_register/mobile_user_register/retrieve.json';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$jsonReturn = curl_exec($ch);
curl_close($ch);
$data = stripslashes($jsonReturn);
json_decode($data);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
echo PHP_EOL;
}
?>
这是 Web 服务 api 的代码......
<?php
function api_mobile_user_register_services_resources() {
$api = array(
'mobile_user_register' => array(
'operations' => array(
'retrieve' => array(
'help' => 'Retrieves mobile user list',
'callback' => 'mobile_user_retrieve',
'access callback' => 'user_access',
'access arguments' => array('access content'),
'access arguments append' => FALSE,
'args' => array(
array(
'name' => 'fn',
'type' => 'string',
'description' => 'Function to perform',
'source' => array('path' => '0'),
'optional' => TRUE,
'default' => '0',
),
array(
'name' => 'phone_no',
'type' => 'string',
'description' => 'get user id and activate_code by phone_no',
'source' => array('param' => 'phone_no'),
'optional' => TRUE,
'default' => '0',
),
),
),
),
),
);
return $api;
}
?>
<?php
function mobile_user_retrieve($fn,$phoneNo) {
$query = db_select('mobile_users', 'n');
$query->fields('n');
$items = $query->execute()->fetchAll();
$reply= array('status' => '1','mobile_user' => $items) ;
return $reply;
}
?>
【问题讨论】: