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.