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?
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"));
please prefer this Microsoft documentation.
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-7-0
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"}
Related
I have an data model in C#:
public class RootObjectData
{
public Person person { get; set; }
public Parameters parameters { get; set; }
public Indicators indicators { get; set; }
}
I tried to send this data as raw JSON using RestSharp:
public string send(RootObjectData data) {
var client = new RestClient(RestfulPaths.BASE_URL);
var request = new RestRequest(RestfulPaths.GET_ANALYS, Method.POST);
request.AddJsonBody(data);
request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
}
But it send wrong format data.
I fill data like this:
RootObjectData bioModel = new RootObjectData();
bioModel.person = new Person();
bioModel.indicators = new Indicators();
bioModel.parameters = new Parameters();
If to use POSTman a correct data is (raw JSON):
{
"person": {
},
"parameters": {
},
"indicators": {
}
}
I try to attain this sending data object in C#
I need to write the titles of the countries from VK API to a list from the following link.
I have written some code:
public class GettingCountry
{
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
var readJson = JObject.Parse(jsonString);
string countryName = readJson["response"]["items"].ToString();
var deserialized = JsonConvert.DeserializeObject<RootObject>(jsonString);
return jsonString;
}
}
public class Item
{
public int id { get; set; }
public string title { get; set; }
}
public class Response
{
public int count { get; set; }
public List<Item> items { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
}
I put a breakpoint and got in string countryName only this:
As you can see the VK API returns you an array of objects.
Your jsonString contains full response string. Now, jsonString["response"]["items"] contains an array of items.
First you need to parse the array and then parse each item, like this:
var readJson = JObject.Parse(jsonString);
JArray countries = JArray.Parse(readJson["response"]["items"]);
var Response listOfCountries = new Response();
foreach (var country in countries) {
Item currentCountry = new Item();
currentCountry.id = country.id;
currentCountry.title = country.title;
listOfCountries.items.Add(currentCountry);
}
listOfCountries.count = listOfCountries.items.Count;
From the code perspective, I would recommend giving proper names to variables, classes, and types to improve code readability and cleanliness. On top of it, I don't really see a point in having a separate Response class. For example, you could rename your Item class and call it Country. All you need to have is a list of countries then. Also, because you're using async method, you want to do the processing of the return within your using for the HttpClient - if you don't the client might be disposed too soon and you might start hitting very weird bugs. Like this:
public class VkCountry
{
public int Id { get; }
public string Title { get; }
public VkCountry(int countryId, string countryTitle) {
this.Id = countryId;
this.Title = countryTitle;
}
}
public async Task<List<VkCountry>> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
var listOfCountries = new List<VkCountry>();
var responseCountries = JArray.Parse(JObject.Parse(jsonString)["response"]["items"].ToString());
foreach (var countryInResponse in responseCountries) {
var vkCountry = new VkCountry((int)countryInResponse["id"], (string)countryInResponse["title"]);
listOfCountries.Add(vkCountry);
}
return listOfCountries;
}
}
You might notice that I've made VkContry implementation immutable, the properties are read-only and can be set using the constructor only. I'd recommend using immutable objects when you are consuming relatively static third-party APIs (list of countries is definitely static, unless some kind of application logic will require you to update the name of the country).
Obviously, you might want to add nullability checks and different validations.
I am calling an external service using GetAsync() and passing parameters in query string. When i check the content in the response, i don't see anything returned, however it returns 200 OK and in fiddler it returns me the XML response correctly. I need the XML response to get de-serialize to an C# object and then further save it to DB.
Things tried:
1) Tried this by adding this setting in global- app_start(), It didn't help
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
2) Created an object and tried to sent it via GetAysnc, that didn't help either.
public class Request
{
[XmlElement]
public string XML { get; set; }
[XmlElement]
public List<string> ProNumber { get; set; }
}
2) Should i try passing parameters in query string and expect json result? if i add mediatyperformatter to application/json?
Here is my code:
public async Task<HttpResponseMessage> GetData()
{
string requestString = "&xml=Y&PRONumber=82040X,03117X";
string result = "";
string url = #"http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController";
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
HttpResponseMessage response = await client.GetAsync(url+requestString);
if (response.IsSuccessStatusCode)
{
return response;
}
}
}
catch (Exception ex)
{
result = ex.Message;
}
return null;
}
EDIT:
Shipments scp = null;
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Shipment";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(Shipment), xRoot);
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
{
scp = (Shipments)serializer.Deserialize(stream);
}
Model:
public class Shipments
{
[XmlArrayItem(Type = typeof(Shipment))]
public Shipment[] Shipment;
}
public class Shipment
{
[XmlAttribute()]
public int returnCode { get; set; }
.................
..............
Getting error:<SHIPMENTS xmlns=''> was not expected.
Any help on this is much appreciated.
Thanks,
WH
This worked for me -
var client = new HttpClient();
var data = client.GetStringAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
var ser = new XmlSerializer(typeof(Shipments));
var t = (Shipments)ser.Deserialize(new StringReader(data));
public class Shipment
{
public string returnCode { get; set; }
public string returnMessage { get; set; }
public string freightBillNumber { get; set; }
//props
}
[XmlRoot(ElementName = "SHIPMENTS")]
public class Shipments
{
[XmlElement(ElementName = "SHIPMENT")]
public List<Shipment> SHIPMENT { get; set; }
}
EDIT
this works as well -
var data = client.GetStreamAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
EDIT
works as well -
var client = new HttpClient();
var data = client.GetAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
var ser = new XmlSerializer(typeof(Shipments));
var t = (Shipments)ser.Deserialize(data.Content.ReadAsStreamAsync().Result);
[{
"channel_id":299,
"requests":[{
"order_id":3975,
"action":"REQUEST_LABELS"
}]
}]
How to create the above request in c# the requests can be multiple.
I am new to c# i tried the below:
Dictionary<long, List<object>> requestObject = new Dictionary<long, List<object>>();
List<object> listrequestObjects = new List<object>();
Request requestOb = new Request();
requestOb.order_id = 2372;
requestOb.action = "REQUEST_LABELS";
listrequestObjects.Add(requestOb);
requestObject.Add(2352635, listrequestObjects);
string requesttest = JsonConvert.SerializeObject(requestObject);
But getting a weird request. Please help.
The structure should look like :
public class Request
{
public int order_id { get; set; }
public string action { get; set; }
}
public class RootObject
{
public int channel_id { get; set; }
public List<Request> requests { get; set; }
}
You need to declare the root object also:
[Serializable]
public class Root {
public int channel_id;
public Request[] requests;
}
Then assign the value and serialize it:
var root = new Root();
root.channel_id = 299;
root.requests = listrequestObjects.ToArray();
string requesttest = JsonConvert.SerializeObject(root);
You can use Newtonsoft.Json.
try this
private JArray GetResponse()
{
var main_array = new JArray();
var channel_id = new JObject();
channel_id.Add("channel_id",299);
var request = new JArray();
var order_id = new JObject();
order_id.Add("order_id",3975);
var action = new JObject();
action.Add("action","REQUEST_LABELS");
request.Add(order_id);
request.Add(action);
main_array.Add(channel_id);
main_array.Add(request);
return main_array;
}
Please try the JavaScriptSerializer class available in namespace
using System.Web.Script.Serialization
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(requestObject);
The requestObject list is your custom class with all necessary properties.
Thanks
I want to create Webinar in GoToWebinar using Citrix API. I am having following code:
public class CreateWebinarTime
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
public class NewWebinar
{
public string subject { get; set; }
public string description { get; set; }
public List<CreateWebinarTime> Times { get; set; }
public string timeZone { get; set; }
}
string uri = #"https://api.citrixonline.com/G2W/rest/organizers/[ORGKEY]/webinars";
CreateWebinarTime t = new CreateWebinarTime();
t.StartTime = DateTime.Now.AddDays(2);
t.EndTime = t.StartTime.AddHours(2);
List<CreateWebinarTime> tempList = new List<CreateWebinarTime>();
tempList.Add(t);
var newWebinar = new NewWebinar
{
subject="Webinar Test",
description="This is a test webinar.. Will be deleted soon",
Times = tempList,
timeZone = "Asia/Calcutta"
};
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(newWebinar);
WebClient client = new WebClient();
client.Headers = new WebHeaderCollection();
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-type", "application/json");
client.Headers.Add("Authorization", string.Format("OAuth oauth_token={0}", OauthToken));
string resp = client.UploadString(uri, "POST", json);
It is showing me error "The webinar subject, start or end time are missing" even though I am passing value. I am sure there is no problem with subject, so there is problem with time.
The json created is: {"subject":"Webinar Test","description":"This is a test webinar.. Will be deleted soon","Times":[{"StartTime":"/Date(1424233883641)/","EndTime":"/Date(1424241083641)/"}],"timeZone":"Asia/Calcutta"}
Please help me to fix this.
I solved it myself.
Json is case sensititve and I made mistake over there.
Used 'Times' instead of 'times', 'StartTime' instead of 'startTime' and 'EndTime' instead of 'endTime'