我将数据从Vb.net客户端发布到PHP rest api,但由于某种原因,json_decode不能处理传递的字符串。 发布到服务器的代码是:
Dim payload As String = "{""key"":""Test"",""bookings"":" & txtUpload.Text & "}"
Dim request As WebRequest = WebRequest.Create(String.Format(baseAPIImportUrl))
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim byteArray() As Byte = Encoding.UTF8.GetBytes(payload)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse
' Display the status.
MessageBox.Show(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream
' Open the stream using a StreamReader for easy access.
Dim reader As StreamReader = New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd
' Display the content.
' Console.WriteLine(responseFromServer)
MessageBox.Show(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
正在传递的值:
{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }
在PHP方面我做:
$bookings = $_POST->bookings
$data = json_decode($bookings,true);
$total = count($data['booking']);
$ total应显示1,因为预订数组中有1个项目,但总是显示为0
答案 0 :(得分:6)
$_POST->bookings
- 这是你的问题。 ->
是对象访问运算符,但在PHP中,$_POST
不是对象而是数组。
如果您将此值作为表单数据的一部分提交,通常可以通过VB代码中的数组语法(例如$_POST['bookings']
),但访问它,您可以实际上将JSON字符串作为POST正文发布。
在PHP中,您可以像这样访问原始POST主体:
$bookings = file_get_contents('php://input');
其余代码应该照常工作。
编辑:实际上,你也有错字。尝试
$total = count($data['bookings']);
// or
$total = count($data['bookings']['booking']);
答案 1 :(得分:1)
还有一个json数组。试试这个。
<?php
$data='{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }';
$data = json_decode($data,true);
echo '<pre>';
print_r($data);
$total = count($data['bookings']['booking']);
echo $total;
答案 2 :(得分:1)
$ data = json_decode($ bookings, true );
这里根据php文档,json_decode函数中的sencond参数表示返回输出为对象还是数组
参数2 = true (将返回数组)
参数2 = false (将返回对象,它是默认值)
json_decode生成以下数组
Array
(
[key] => 91a1522Test
[bookings] => Array
(
[booking] => Array
(
[0] => Array
(
[ClassId] => 4
[ClassName] => THOASC
[YearWeek] => 1751
)
)
)
)
因此,应该像计数一样访问($ data [&#39;预订&#39;] [&#39;预订&#39;])
答案 3 :(得分:0)
如果我看到正确,你的根目录"key"
和"bookings"
对象,"bookings"
对象里面有"booking"
数组。
因此,访问大小的正确方法应该是
count($data['bookings']['booking']);