-3

I'm trying to convert the following code snippet from PHP to C# or VB.NET This is from a PHP page which is used to catch a JSON string from an external webhook.

// 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: I've got the json string from the stream now. Still trying to figure out how to parse this. The JSON string format is out of my control, but I essentially need to get the "properties" node.

WhiskerBiscuit
  • 4,795
  • 8
  • 62
  • 100
  • just google "Open and read file c#"... – devHead Oct 26 '12 at 19:30
  • 1
    And how far have you gotten? Post some C#/VB.NET code that you tried – Bogdan Oct 26 '12 at 19:30
  • haven't gotten very far, as can't figure out my way past the file_get_contents('php://input''). I'm trying to use System.Net.WebClient – WhiskerBiscuit Oct 26 '12 at 19:36
  • Porting code is usually pretty easy. Porting a library (aka framework, dll, api) can be extremely tough. You are trying to port the library (specifically, a function embedded in the PHP framework). I don't think you are going to find an easy or helpful way to do this. – JDB Oct 26 '12 at 19:58
  • [This answer](http://stackoverflow.com/a/5515894/351330) would point you in the right direction on how to write a stream to a file (the stream in your case being [Request.InputStream](http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx)). To handle the JSON part look at @YYY's answer. – Bogdan Oct 26 '12 at 20:03
  • Spider that did it for me! Thanks! – WhiskerBiscuit Oct 26 '12 at 20:14
  • 1
    @WhiskerBiscuit I've turned my comment into an answer if you want to mark it as the solution to your problem. – Bogdan Oct 26 '12 at 20:20

4 Answers4

2

This answer would point you in the right direction on how to write a stream to a file. The stream in your case being Request.InputStream which is the equivalent of php://input.

To handle the JSON part look at @YYY's answer.

Community
  • 1
  • 1
Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • You might want to take a look at #6 in this [meta question](http://meta.stackexchange.com/a/118694/148672) – Conrad Frix Oct 26 '12 at 22:23
  • @ConradFrix Thank you for pointing me towards that post as the guidelines there are very helpful. But I'm not sure if #6 is the case here. The answer I am linking to is meant merely to provide a starting point for the OP and it only provides part of the solution to the question being asked here. Please let me know if I'm misinterpreting something. – Bogdan Oct 26 '12 at 22:38
1

.NET's base libraries don't have any really good ways to handle JSON input. Instead, take a look at Json.NET, which is a high performance 3rd party library for just this need.

There are usage examples on the linked page.

tmesser
  • 7,558
  • 2
  • 26
  • 38
1

Here is essentially what you are trying to do if I understand correctly. But as others mentioned. JSON.NET is the better option.

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]);
        }
    }
}

credit to this guy

corylulu
  • 3,449
  • 1
  • 19
  • 35
  • I'm a little stuck on the custom Dictionary. Your code is deserializing partially, but the "inner" properties of the JSON appears to be missing – WhiskerBiscuit Oct 26 '12 at 21:19
  • The JSON is coming from an external site, and it appears to have arrays within arrays. Not sure how to post it here, as it is a mess – WhiskerBiscuit Oct 26 '12 at 21:36
  • Unfortinately, I don't have the proper setup without your direct code to see this JSON. But I think it would be a matter of modifying the MyCustomDict to look for embeded arrays within the foreach loop. – corylulu Oct 26 '12 at 21:42
0

Since you heartless thugs dinged me, I feel obligated to at least document my progress.

   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
WhiskerBiscuit
  • 4,795
  • 8
  • 62
  • 100