【问题标题】:Convert code snippet from PHP to C# or VB.NET [closed]将代码片段从 PHP 转换为 C# 或 VB.NET [关闭]
【发布时间】:2012-10-17 02:08:22
【问题描述】:

我正在尝试将以下代码 sn-p 从 PHP 转换为 C# 或 VB.NET 这是来自用于从外部 webhook 捕获 JSON 字符串的 PHP 页面。

// Get the POST body from the Webhook and log it to a file for backup purposes...
$request_body = file_get_contents('php://input');
$myFile = "testfile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $request_body);
fclose($fh);

// Get the values we're looking for from the webhook
$arr = json_decode($request_body);
foreach ($arr as $key => $value) {
    if ($key == 'properties') {
        foreach ($value as $k => $v) {
            foreach ($v as $label => $realval) {
                if ($label == 'value' && $k == 'zip') {
                    $Zip = $realval;                    
                }
                elseif($label == 'value' && $k == 'firstname') {
                    $Fname = $realval;
                }
                elseif($label == 'value' && $k == 'lastname') {
                    $Lname = $realval;
                }
                elseif($label == 'value' && $k == 'email') {
                    $Email = $realval;
                }
                elseif($label == 'value' && $k == 'phone') {
                    $Phone = $realval;
                    $Phone = str_replace("(", "", $Phone);
                    $Phone = str_replace(")", "", $Phone);
                    $Phone = str_replace("-", "", $Phone);
                    $Phone = str_replace(" ", "", $Phone);
                }
                //need the other values as well!
            }
        }
    }
}

ETA:我现在从流中得到了 json 字符串。仍在试图弄清楚如何解析这个。 JSON 字符串格式不在我的控制范围内,但我基本上需要获取“属性”节点。

【问题讨论】:

  • 只是谷歌“打开并读取文件 c#”...
  • 你走了多远?发布一些您尝试过的 C#/VB.NET 代码
  • 还没有走得很远,因为我无法通过 file_get_contents('php://input'')。我正在尝试使用 System.Net.WebClient
  • 移植代码通常很容易。移植一个库(又名框架、dll、api)可能非常困难。您正在尝试移植库(特别是嵌入在 PHP 框架中的函数)。我认为您不会找到一种简单或有用的方法来做到这一点。
  • @WhiskerBiscuit 如果您想将我的评论标记为您的问题的解决方案,我已将其转化为答案。

标签: c# php vb.net json


【解决方案1】:

This answer 将为您指明如何将流写入文件的正确方向。在您的情况下,流是Request.InputStream,相当于php://input

要处理 JSON 部分,请查看 @YYY 的答案。

【讨论】:

  • 你可能想看看meta question中的#6
  • @ConradFrix 感谢您将我指向该帖子,因为那里的指南非常有帮助。但我不确定#6 是否是这种情况。我链接到的答案仅仅是为 OP 提供一个起点,它只提供了这里提出的问题的部分解决方案。如果我误解了某些内容,请告诉我。
【解决方案2】:

.NET 的基础库没有任何真正好的方法来处理 JSON 输入。相反,请查看 Json.NET,这是一个高性能的 3rd 方库,可满足此需求。

链接页面上有使用示例。

【讨论】:

    【解决方案3】:

    如果我理解正确,这基本上就是您要尝试做的事情。但正如其他人提到的那样。 JSON.NET 是更好的选择。

    private void Request()
    {
        //Makes Request
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/Test.php");
        request.ContentType = "application/json; charset=utf-8";
        request.Accept = "application/json, text/javascript, */*";
        request.Method = "POST";
        using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
        {
            writer.Write("{id : 'test'}");
        }
    
        //Gets response
        WebResponse response = request.GetResponse();
        Stream stream = response.GetResponseStream();
        string json = "";
        using (StreamReader reader = new StreamReader(stream))
        {
            //Save it to text file
            using (TextWriter savetofile = new StreamWriter("C:/text.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    savetofile.WriteLine(line);
                    json += line;
                }
            }
        }
    
        //Decodes the JSON
        DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(MyCustomDict));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
        MyCustomDict dict = (MyCustomDict)dcjs.ReadObject(ms);
    
        //Do something with values.
        foreach(var key in dict.dict.Keys)
        {
            Console.WriteLine( key);
            foreach(var value in dict.dict[key])
            {
                Console.WriteLine("\t" + value);
            }
        }
    
    }
    [Serializable]
    public class MyCustomDict : ISerializable
    {
        public Dictionary<string, object[]> dict;
        public MyCustomDict()
        {
            dict = new Dictionary<string, object[]>();
        }
        protected MyCustomDict(SerializationInfo info, StreamingContext context)
        {
            dict = new Dictionary<string, object[]>();
            foreach (var entry in info)
            {
                object[] array = entry.Value as object[];
                dict.Add(entry.Name, array);
            }
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            foreach (string key in dict.Keys)
            {
                info.AddValue(key, dict[key]);
            }
        }
    }
    

    感谢this guy

    【讨论】:

    • 我有点卡在自定义词典上。您的代码正在部分反序列化,但 JSON 的“内部”属性似乎缺失
    • JSON 来自外部站点,它似乎在数组中有数组。不知道如何在这里发布,因为它是一团糟
    • 不幸的是,如果没有您的直接代码,我没有正确的设置来查看此 JSON。但我认为这将是修改 MyCustomDict 以在 foreach 循环中查找嵌入数组的问题。
    【解决方案4】:

    既然你们这些无情的暴徒欺负我,我觉得至少有义务记录下我的进步。

       Using inputStream As New StreamReader(Request.InputStream)
            JSON = inputStream.ReadToEnd
            If JSON.Length > 0 Then
                Using writer As StreamWriter = New StreamWriter("c:\temp\out.txt")
                    writer.Write(JSON)
                End Using
            End If
        End Using
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 2012-02-09
      • 2023-03-09
      • 2010-10-01
      • 2010-11-19
      • 2013-09-17
      • 2016-12-17
      相关资源
      最近更新 更多