php – 无法使用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->预订 – 这是你的问题. – &GT是对象访问操作符,但在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']);

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...