1

我一直在到处研究以解决这个问题,但我每次都碰壁。目标是将数据序列化为 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));
4

1 回答 1

2

Instead of using DataContractSerializer Use DataContractJsonSerializer or JavaScriptSerializer in your C# code

DataContractJsonSerializer Class Docs
JavaScriptSerializer Class Docs

于 2012-09-25T18:50:51.290 回答