Saturday, December 27, 2014

How to send Json data using C#:


      suppose we have to send certain data as json post over wire using c#  for that we have construct corresponding poco class as follows where each property correspond with field to post. 
   Other option is to create json string on your own.

POCO CLASS:

public class PocoJsonData
{
public string CellNo
{
get; set;
}
public string Brand
{
get;set;
}
public string Seller
{
get;set;
}
public string Region
{
get;set;
}
public string ContentType
{
get;set;
}
public string ItemCode
{
get;set;
}
public string ItemName
{
get;set;
}
public string ContentPrice
{
get;set;
}
public string DiscountedPrice
{
get;set;
}
public string BillDate
{
get; set;
}
public string Address
{
get; set;
}
}

public const string token="ffghfgfgjfjfjfjfjhfjfgfgkuhjhhkhj";

public string DoJsonPost(
string CellNo, string Brand, string Seller, string Region,
string ContentType, string ItemCode, string ItemName, string ContentPrice, string
DiscountedPrice, string BillDate,string Address)
{
string result = "";
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
//action to which data to post
string url = "https://abc.com/pqr/lmn";


PocoJsonData data = new PocoJsonData
{
CellNo = Convert.ToString(CellNo).Trim(),
Brand = Convert.ToString(Brand).Trim(),
Seller = Convert.ToString(Seller).Trim(),
Region = Convert.ToString(Region).Trim(),
ContentType = Convert.ToString(ContentType).Trim(),
ItemName = Convert.ToString(ItemName).Trim(),
ContentPrice = Convert.ToString(ContentPrice).Trim(),
DiscountedPrice = Convert.ToString(DiscountedPrice).Trim(),
BillDate = Convert.ToString(BillDate).Trim(),
ItemCode = Convert.ToString(ItemCode).Trim() ,
Address = Convert.ToString(Address).Trim()
}; 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, data);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
System.Net.HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream(), Encoding.Default))
{
result = reader.ReadToEnd();
}
webresponse.Close();
return result;
}

    Here we are setting up content type as application/json to tell receiver of data , data received is of format json.

    Data to be posted has been assigned to poco class object instance properties,then the instance of object has been serialized to json string then using HttpWebRequest class we will post data and get response from other side

No comments:

Post a Comment