如何在发出 POST 请求时在 json 请求中传递传入的整数参数值

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

为 API 发出 POST 请求,将传入的 json 正文作为硬编码字符串传递。所有硬编码值都很好,只需要根据传入参数 incomingID (int)

传递 ID

检查了几个 articles/questions,但没有任何明确的答案。请suggest/guide如何用传入参数值(incomingID)替换这个硬编码值123456

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;
            }
        }

为此,您可以使用简单的插值法:

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}}}}}}}"

请注意,左括号和右括号应重复两次以转义它们。但是,这种制作 JSON 字符串的方式很奇怪而且并不常见。最好使用 序列化 来实现您的目标。例如,使用 Newtonsoft.Json nuget 来(反)序列化您的对象。您需要做什么:

  1. 单独创建模型 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. 创建您的 Information class:
  2. 的实例
var information = new Information(new MessageHeader("getInfo", DateTime.Now, $"{DateTime.Now}-12345", PayloadFormat.V1, incomingID));
  1. 序列化你的字符串(确保你是using Newtonsoft.Json;):
var json = JsonConvert.SerializeObject(information);

然后根据需要使用您的 json。结果将是:

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