无法将C#中的JSON数据发送到PHP服务器

时间:2012-09-25 18:47:19

标签: c# php json

我一直在到处研究解决这个问题,但我每次都会碰壁。目标是将数据序列化为JSON字符串,并将该数据发送到服务器上的PHP文件。最终结果是json_decode读出null。我已经在这个工作了几个小时,任何人的任何指导或解决方案将不胜感激。这是我的代码片段。

private void sendData(string questionId, string youtubeUrl)
    {

        //fill in class data
        videoData vd = new videoData();
        vd.question_id = questionId;
        vd.video_path_on_server = videoId;

        //specifiy the url you want to send data to
        string phpurl = "http://questionoftheweek.local/video/save";

        //make request to url and set post properties
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(phpurl);
        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";

        try
        {
            //serialize
            DataContractSerializer ser = new DataContractSerializer(typeof(videoData));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, vd);

            string videodata = Encoding.UTF8.GetString(ms.ToArray());
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(videodata);
            writer.Close();
        }
        catch (Exception ex) {
            MessageBox.Show("Unable to send data: " + ex.Message);
        }

这是我正在使用的服务器上的PHP代码:

<?php
$json = json_encode($_POST);
var_dump(json_decode($json));

1 个答案:

答案 0 :(得分:2)

而不是在您的C#代码中使用DataContractSerializer使用DataContractJsonSerializerJavaScriptSerializer

DataContractJsonSerializer Class Docs
JavaScriptSerializer Class Docs