[英]Not being able to json_decode
我將數據從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
$_POST->bookings
- 這是你的問題。 ->
是對象訪問運算符,但在PHP中, $_POST
不是對象而是數組。
如果您將此值作為表單數據的一部分提交,您通常會通過數組語法訪問它(例如$_POST['bookings']
), 但是從VB代碼中,您實際上是將JSON字符串作為POST主體本身發布。
在PHP中,您可以像這樣訪問原始POST主體:
$bookings = file_get_contents('php://input');
然后你的其余代碼應該像往常一樣工作。
編輯:實際上,你也有一個錯字。 嘗試
$total = count($data['bookings']);
// or
$total = count($data['bookings']['booking']);
那里還有一個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;
$ 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
)
)
)
)
因此應該像count一樣訪問它($ data ['bookings'] ['booking'])
如果我沒有看到它,你有"key"
和"bookings"
在根和內部對象"bookings"
的對象是"booking"
陣列。 因此,訪問大小的正確方法應該是
count($data['bookings']['booking']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.