Ismail Bhyat

Ismail Bhyat

  • NA
  • 58
  • 0

c# Json Post Parameters

Oct 21 2013 7:21 AM

I am trying to post data to a json api. this is how my code looks. It's returning an error from the server, the guys up there are telling me that i'm sending everything as a json string and that i should post params of which only one parameter is a JSON stirng. ie. contact_attributes which should contain a string like the one below:

"{\"name\":\"Leigh\",\"surname\":\"Duddy\",\"passport_number\":\" 00000020\",\"unique_identifier\":\"7353280000000020\",\"msisdn\": \"27829042259\",\"bank_account_number\":null,\"bank_account_br anch_code\":null,\"bank_account_branch_name\":null,\"bank_detai ls_required\":false,\"membership_number\":null,\"bank_account_b ank_id\":null,\"bank_account_account_type_id\":null,\"bank_accou nt_initials\":null,\"bank_account_surname\":null,\"bank_account_p assport_number\":null,\"date_of_birth\":null,\"debit_day\":null,\"con tract_sale_date\":null,\"contract_start_date\":null}"

I am totally confused, does anyone know how i can do this.

public class JsonSaleData
    {
        [DataMember]
        public string contact_attributes { get; set; }
        [DataMember]
        public string campaign_uuid = "9d119cce-25ea-46bc-b7bc-cba7e8323e91";
        [DataMember]
        public string user_credentials = "OCPdNbeltviij8C1RLcf";
        [DataMember]
        public string license_id = "1";

    }

private string PostSaleToClient(string url, JsonSaleData _SaleData)
        {


            string strResult = "";
            try
            {
                ASCIIEncoding encoding = new ASCIIEncoding();


                System.Net.HttpWebRequest httpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json; charset=utf-8";


                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(JsonSaleData));
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, _SaleData);
                ms.Position = 0;
                String json = Encoding.UTF8.GetString(ms.ToArray());


                StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                System.Net.HttpWebResponse httpWebResp = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpWebResp.GetResponseStream()))
                {
                     strResult = streamReader.ReadToEnd();
                }

                return strResult;

            }
            catch (Exception ex)
            {
                string e = ex.Message;
            }

           return strResult;


        }