I have been tasked to receive a JSON payload to my API that was made to recieve http post variables. We are going to receive the request stream and convert it into a byte array, then DeSerialize the JSON using the Newtonsoft JSON .Net package. When we are finished, we will have a Dictionary object with the contents of the JSON payload. This technique will only work for a single JSON object, as the dictionary can only hold a unique key and value (id:1, text:This is the text)
We will need to get the total number of bytes in the stream to set the array length.
// set a variable to hold the incoming stream. System.IO.Stream str; // set two variables for the stream array Int32 strLen, strRead; // Create a Stream object. str = Request.InputStream; // Find number of bytes in stream. strLen = Convert.ToInt32(str.Length); // Create a byte array. byte[] strArr = new byte[strLen]; // Read stream into byte array. strRead = str.Read(strArr, 0, strLen); // change they bytes into UTF8 text string response = Encoding.UTF8.GetString(strArr); // convert the JSON object into a .net dictionary Dictionary<string, string> MyData = JsonConvert.DeserializeObject<Dictionary<string, string>>(response); // display the JSON payload for debugging LabelPostVars.Text = response;