我正在编写一个自定义的REST API演示;现在它可以在演示中返回数字和字符串,但是我希望它像其他REST API一样返回JSON对象。
在我的演示中,我使用curl 调用了Magento 2 API(即,获取客户信息:http://localhost/index.php/rest/V1/customers/1),它返回一个JSON字符串:
“ {\” id \“:1,\” group_id \“:1,\” default_billing \“:\” 1 \“,\” created_at \“:\” 2016-12-13 14:57:30 \“ ,\“ updated_at \”:\“ 2016-12-13 15:20:19 \”,\“ created_in \”:\“默认商店视图\”,\“电子邮件\”:\“ 75358050@qq.com \ “,\”名字\“:\” azol \“,\”姓氏\“:\”年轻\“,\” store_id \“:1,\”网站ID \“:1,\”地址\“:[{ \“ id \”:1,\“ customer_id \”:1,\“ region \”:{\“ region_code \”:\“ AR \”,\“ region \”:\“ Arad \”,\“ region_id \“:279},\” region_id \“:279,\” country_id \“:\” RO \“,\” street \“:[\” abc \“],\”电话\“:\” 111 \ “,\”邮政编码\“:\”1111 \“,\” city \“:\” def \“,\”名字\“:\” azol \“,\”姓氏“:\”年轻\“,\” default_billing \“:true}], \“ disable_auto_group_change \”:0}“
响应是一个JSON字符串,但是所有键中都包含一个斜杠。我知道我可以用删除斜线str_replace
,但这是一种愚蠢的方法。还有其他方法可以在键中不带斜杠的情况下返回JSON对象吗?
************更新2016.12.27 ************
我在这里粘贴了测试代码:
$method = 'GET';
$url = 'http://localhost/index.php/rest/V1/customers/1';
$data = [
'oauth_consumer_key' => $this::consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $this::accessToken,
'oauth_version' => '1.0',
];
$data['oauth_signature'] = $this->sign($method, $url, $data, $this::consumerSecret, $this::accessTokenSecret);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ','),
'Content-Type: application/json'
],
]);
$result = curl_exec($curl);
curl_close($curl);
// this code has slash still
//return stripslashes("hi i\" azol");
// has slashes still
//return stripcslashes("{\"id\":1,\"group_id\":1,\"default_billing\":\"1\",\"created_at\":\"2016-12-13 14:57:30\",\"updated_at\":\"2016-12-13 15:20:19\",\"created_in\":\"Default Store View\",\"email\":\"75358050@qq.com\",\"firstname\":\"azol\",\"lastname\":\"young\",\"store_id\":1,\"website_id\":1,\"addresses\":[{\"id\":1,\"customer_id\":1,\"region\":{\"region_code\":\"AR\",\"region\":\"Arad\",\"region_id\":279},\"region_id\":279,\"country_id\":\"RO\",\"street\":[\"abc\"],\"telephone\":\"111\",\"postcode\":\"1111\",\"city\":\"def\",\"firstname\":\"azol\",\"lastname\":\"young\",\"default_billing\":true}],\"disable_auto_group_change\":0}");
// has slashes still
//return json_encode(json_decode($result), JSON_UNESCAPED_SLASHES);
// this code will throw and expcetion:
// Undefined property: *****\*****\Model\Mycustom::$_response
//return $this->_response->representJson(json_encode($data));
return $result;
$json_string = stripslashes($result)
和return json_decode($json_string, true);
return json_encode($result, JSON_UNESCAPED_SLASHES);
吗?