I made a post request class that I could re-use to make POST requests to an external api and return the objects they send me (JSON):
class PostRequest
{
To get the response data you need to call GetResponseStream() on the HttpWebResponse object and then read from the stream. Something like this:
using (Stream s = response.GetResponseStream())
{
using (TextReader textReader = new StreamReader(s, true))
{
jsonString = textReader.ReadToEnd();
}
}
To get the data from the json string, you need to create a data contract class to describe the json data exactly like this:
[DataContract]
public class ApiData
{
[DataMember(Name = "name")] <--this name must be the exact name of the json key
public string Name { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
}
Next you can deserialize the json object from the string:
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ApiData));
ApiData obj = (ApiData)serializer.ReadObject(stream);
return obj;
}
WebRequest will work fine, but I would recommend installing the NuGet package for the HttpClient class. It makes life much simpler. for instance, you could make the above request code in just a few lines:
HttpClient httpClient = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), escapedUrl);
HttpResponseMessage response = await httpClient.SendAsync(msg);
In answer to you question below, here is the generic json converter code that I use:
public static class JsonHelper
{
public static T Deserialize(string json)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(stream);
return obj;
}
}
public static string Serialize(object objectToSerialize)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
serializer.WriteObject(ms, objectToSerialize);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
}