Home > other >  How to pass incoming integer parameter value in json request while making a POST request
How to pass incoming integer parameter value in json request while making a POST request

Time:05-19

Making a POST request for the API, passing incoming json body as hardcoded string. Fine with all hardcoded values, only need to pass ID based on incoming parameter incomingID (int)

Checked couple of articles/questions, but didn't any clear answer. Please suggest/guide how to replace this hardcoded value 123456 with incoming parameter value (incomingID)

Replace field in Json file with some other value

How to replace placeholders inside json string?

private void CallAPI(int incomingID)
        {

            const string apiURL = "API URL"; // some test API
            string getInfoResult = string.Empty;

            try
            {
                HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(apiURL);
                webrequest.Method = "POST";
                webrequest.ContentType = "application/json";

                using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
                {
                    string json = "{\"Information\":{\"messageHeader\":{\"message\":\"getInfo\",\"transactionDate\":\"2021-05-11T12:05:54.000\", \"transactionID\":\"2021-05-15T12:05:54.000-12345\",\"payLoadFormat\":\"V1\",\"ID\":123456}}}"; //pass this incomingID based on parameter value

                    streamWriter.Write(json);
                }

                HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();

                Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
                getInfoResult = responseStream.ReadToEnd();
                webresponse.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

CodePudding user response:

To make this, you can use simple interpolation:

string json = $"{{\"Information\":{{\"messageHeader\":{{\"message\":\"getInfo\",\"transactionDate\":\"2021-05-11T12:05:54.000\", \"transactionID\":\"2021-05-15T12:05:54.000-12345\",\"payLoadFormat\":\"V1\",\"ID\":{incomingID}}}}}}}"

Note that open and close brackets should be repeated twice to escape them. But, this is weird and not so common way to make JSON strings. Better use serialization to achieve your goal. For an example, use Newtonsoft.Json nuget to (de)serialize your objects. What you need to do:

  1. Create your models as separate classes:

PayloadFormat.cs

[Newtonsoft.Json.JsonConverter(typeof(StringEnumConverter))] // this string will force your enum serialize as "V1" instead of "0"
public enum PayloadFormat
{
    V1,
    V2,
    V3
}

MessageHeader.cs

public class MessageHeader
{
    public MessageHeader(string message, DateTime transactionDate, string transactionId, PayloadFormat payloadFormat, int id)
    {
        Message = message;
        TransactionDate = transactionDate;
        TransactionId = transactionId;
        PayloadFormat = payloadFormat;
        Id = id;
    }

    public string Message { get; set; }
    public DateTime TransactionDate { get; set; } // change type if you need to
    public string TransactionId { get; set; } // change type if you need to
    public PayloadFormat PayloadFormat { get; set; } // change type if you need to
    public int Id { get; set; }
}

Information.cs

public class Information
{
    public Information(MessageHeader messageHeader)
    {
        MessageHeader = messageHeader;
    }

    public MessageHeader MessageHeader { get; set; }
}
  1. Create an instance of your Information class:
var information = new Information(new MessageHeader("getInfo", DateTime.Now, $"{DateTime.Now}-12345", PayloadFormat.V1, incomingID));
  1. Serialize your string (make sure you are using Newtonsoft.Json;):
var json = JsonConvert.SerializeObject(information);

Then use your json as you need to. The result will be:

{
    "MessageHeader": {
        "Message": "getInfo",
        "TransactionDate": "2022-05-17T19:45:33.2161326 05:00",
        "TransactionId": "17.05.2022 19:45:33-12345",
        "PayloadFormat": "V1",
        "Id": 5
    }
}
  • Related