I'm trying to send List (of strings) as http request to a flask python backend but I cant figure how to parse the list into json format to send that
I tryed this:
var myObject = (dynamic)new JsonObject();
myObject.List = new List<string>();
// add items to your list
according to this: C# HTTP post , how to post with List<XX> parameter? but It's says that List isn't recognized. any help or other method to do this?
CodePudding user response:
Use JsonSerializer in order to convert any object to a string
var list = new List<string>();
httpClient.PostAsync(
"",
new StringContent(
System.Text.Json.JsonSerializer.Serialize(list),
Encoding.UTF8,
"application/json"));
If you need to send an object with a List property:
var list = new List<string>();
httpClient.PostAsync(
"",
new StringContent(
System.Text.Json.JsonSerializer.Serialize(new {List = list}),
Encoding.UTF8,
"application/json"));
CodePudding user response:
please prefer this Microsoft documentation.
using System.Text.Json;
namespace SerializeToFile
{
public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
public class Program
{
public static void Main()
{
var weatherForecast = new WeatherForecast
{
Date = DateTime.Parse("2019-08-01"),
TemperatureCelsius = 25,
Summary = "Hot"
};
string fileName = "WeatherForecast.json";
string jsonString = JsonSerializer.Serialize(weatherForecast);
File.WriteAllText(fileName, jsonString);
Console.WriteLine(File.ReadAllText(fileName));
}
}
}
// output:
//{"Date":"2019-08-01T00:00:00-
07:00","TemperatureCelsius":25,"Summary":"Hot"}