简体   繁体   English

如何正确发送 json object 到 php 后端

[英]How do you send a json object to php backend properly

While using something like this在使用这样的东西时

" "

 Dictionary<string, string> form = new Dictionary<string, string>
  {
      {_metajson, JsonConvert.SerializeObject(metaJson)}
  };
  HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(form));

However on the php side of things with $_Request I get the string and all the quotes are turned into &#34;然而,在 php 方面, $_Request我得到了字符串,所有的引号都变成了&#34; so the json looks like所以 json 看起来像

{&#34;name&#34;:&#34;myname&#34;}

Is there a better way to send json to a php backend?有没有更好的方法将 json 发送到 php 后端?

On the PHP end of things I am simply assigning the json which has now lost the quotes and has weird marks with在 PHP 结束时,我只是分配了 json ,它现在已经丢失了引号并且带有奇怪的标记

$json = $_REQUEST["test"];

The json I am sending is in memory, its not saved to a file anywhere.我发送的 json 在 memory 中,它没有保存到任何地方的文件中。 It is very small like shown above and is needed for the purposes of the application I am writing.它非常小,如上所示,对于我正在编写的应用程序而言是必需的。

Use php://input使用php://input

php://input is a read-only stream that allows you to read raw data from the request body. php://input是只读的 stream,允许您从请求正文中读取原始数据。

Example:例子:

$json_string = file_get_contents('php://input');

//Converting It to PHP object:

$data = json_decode($json_string );

I was just working with the same problem and here is my solution, it works for me我只是在处理同样的问题,这是我的解决方案,它对我有用

$data = $_POST['json'] ;
$json = json_decode($data, true);
echo json_encode($json);

afterwards, you can take the $json variable an do whatever you want to do with it之后,您可以使用 $json 变量做任何您想做的事情

I ended up changing the approach which worked very well我最终改变了效果很好的方法

I simply base64 encoded the json to avoid http changing special characters to odd string formats like " to &#34; and what not.我只是对 base64 编码了 json 以避免 http 将特殊字符更改为奇怪的字符串格式,例如"&#34;等等。

C# side - using this string in the dictionary form C# 端——在字典形式中使用这个字符串

string encodedJson = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metaJson)));

PHP side PHP侧

$encoded_input  = $_REQUEST["metajson"];

$base64_decoded_input = base64_decode($encoded_input, true);
if (!$base64_decoded_input)
{
    // error out
}
$meta_json = json_encode(json_decode($base64_decoded_input));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM