HttpClient with nested POST parameters

Anjali Agarwal 1,426 Reputation points
2024-09-02T03:53:51.3933333+00:00

I want to pass nested parameters with HTTP client POST. How can I achieve this I have the following code:

 string credentials = JsonConvert.SerializeObject(new
 {
    ApiKey= "123456",
 });
HttpClient client = new HttpClient();
  client.BaseAddress = new Uri("https://test/tokens");
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
  HttpRequestMessage request = new HttpRequestMessage();
  request.Method = HttpMethod.Post;
  request.Content = new StringContent(credentials, Encoding.UTF8, "application/json");

My JSON file looks like this. How can I pass all these nested parameters with HTTP client post.

{
    "OrderTotal":null,
    "MerchantCode":"Test1",
    "MerchantKey":"Test2",
    "ServiceCode":"Testservice1",
    
 
    "Phone":"123-456-7899",
    "Email":"test@test.com",
    "CustomerId" : null,
    "CompanyName" : "",
    "CustomerAddress":{
        "Name":"Thomas jefferson",
        "Address1":"123 test drive",
        "Address2":"",
        "City":"LCK",
        "State":"MI",
        "Zip":"12345",
        "Country":"US"
    },
    "LineItems":
    [
        {
        "Sku":"TEST",
        "Description":"Test",
        "UnitPrice":100.00,
        "Quantity":1
        }
       
    ]
}

I defined these two classes too:

 public class MainParametrs
    {
        public string MerchantCode { get; set; }
        public string MerchantKey { get; set; }
        public string ServiceCode { get; set; }
        public string UniqueTransId { get; set; }
        public string LocalRef { get; set; }
        public string SuccessUrl { get; set; }
        public string FailureUrl { get; set; }
        public string DuplicateUrl { get; set; }
        public string CancelUrl { get; set; }
        public string Phone { get; set; }
        public string CustomerAddress { get; set; }
        public string LineItems { get; set; }
    }
}
    public class CustomerAddressParam
    {
        public string Name { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public string Country { get; set; }
    }

Any help will be highly appreciated.
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,855 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 44,516 Reputation points Microsoft Vendor
    2024-09-02T06:27:02.08+00:00

    Hi @Anjali Agarwal , Welcome to Microsoft Q&A,

    To send a JSON object containing nested parameters using HttpClient, you can construct the nested objects into classes, then instantiate and serialize these classes into JSON. Based on the JSON structure you provide, you can modify your class definition and use System.Text.Json to generate a JSON string, which can then be used as the content of the HttpClient POST request.

    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Text.Json;
    using System.Threading.Tasks;
    
    public class MainParameters
    {
        public string MerchantCode { get; set; }
        public string MerchantKey { get; set; }
        public string ServiceCode { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string CustomerId { get; set; }
        public string CompanyName { get; set; }
        public CustomerAddressParam CustomerAddress { get; set; }
        public LineItemParam[] LineItems { get; set; }
    }
    
    public class CustomerAddressParam
    {
        public string Name { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public string Country { get; set; }
    }
    
    public class LineItemParam
    {
        public string Sku { get; set; }
        public string Description { get; set; }
        public decimal UnitPrice { get; set; }
        public int Quantity { get; set; }
    }
    
    class Program
    {
        static async Task Main(string[] args)
        {
            var parameters = new MainParameters
            {
                MerchantCode = "Test1",
                MerchantKey = "Test2",
                ServiceCode = "Testservice1",
                Phone = "123-456-7899",
                Email = "test@test.com",
                CustomerId = null,
                CompanyName = "",
                CustomerAddress = new CustomerAddressParam
                {
                    Name = "Thomas Jefferson",
                    Address1 = "123 test drive",
                    Address2 = "",
                    City = "LCK",
                    State = "MI",
                    Zip = "12345",
                    Country = "US"
                },
                LineItems = new LineItemParam[]
                {
                    new LineItemParam
                    {
                        Sku = "TEST",
                        Description = "Test",
                        UnitPrice = 100.00M,
                        Quantity = 1
                    }
                }
            };
    
            string json = JsonSerializer.Serialize(parameters);
            
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://test/tokens");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
                request.Content = new StringContent(json, Encoding.UTF8, "application/json");
    
                HttpResponseMessage response = await client.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Request succeeded!");
                }
                else
                {
                    Console.WriteLine("Request failed: " + response.StatusCode);
                }
            }
        }
    }
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.