gpt4 book ai didi

php - 无法进行 json_decode

转载 作者:可可西里 更新时间:2023-11-01 00:12:27 25 4
gpt4 key购买 nike

我正在将数据从 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']);

关于php - 无法进行 json_decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com