Thursday, June 28, 2012

C# deserialize JSON post


[Serializable]
public class Person
{
  public int personId;
  public int appId;
  public string name;
}
 
string input = new StreamReader(Request.InputStream).ReadToEnd();
JavaScriptSerializer deserializer = new JavaScriptSerializer();

Person _person = deserializer.Deserialize(input);
Console.Writeline(string.Format("Person delivered is: {0}", _person.name));

You can test this with the code below --------------------------------------------------:

string url = "the_test_url";
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
StringBuilder jsonData = new StringBuilder();

jsonData.AppendLine("{");
jsonData.AppendLine("\"personId\" : 1234,");
jsonData.AppendLine("\"appId\" : 2334,");
jsonData.AppendLine("\"name\" : \"John\"");
jsonData.Append("}");

byte[] dataArray = Encoding.UTF8.GetBytes(jsonData.ToString());
httpReq.Method = @"POST";
httpReq.ContentType = @"application/json";
httpReq.ContentLength = dataArray.Length;
httpReq.Timeout = 60000; // 1 minute (in milliseconds)
httpReq.KeepAlive = false;

using (Stream requestStream = httpReq.GetRequestStream())
{
  requestStream.Write(dataArray, 0, dataArray.Length);
  requestStream.Flush();
  requestStream.Close();
}
HttpWebResponse _resp = (HttpWebResponse)httpReq.GetResponse();
_resp.Close();

No comments: