How to Deserialize JSON in RestSharp? - c#

I am just beginning developing using RestSharp and have hit an early roadblock. I think once I understand this simple, but key, concept, I should be off and running. I need to return an Access Token before making my standard calls later. I have set up the following classes, generated from json2csharp.com:
public class AccessToken
{
public string Instance_Url { get; set; }
public string Token { get; set; }
public string Expiration_date { get; set; }
public string Refresh_Token { get; set; }
}
public class RootObject
{
public AccessToken Access_Token { get; set; }
}
I have coded the following on a button click:
var tokenclient = new RestClient();
tokenclient.BaseUrl = "https://url";
tokenclient.Authenticator = new HttpBasicAuthenticator("username", "password");
var tokenrequest = new RestRequest(Method.GET);
tokenrequest.RequestFormat = DataFormat.Json;
IRestResponse tokenresponse = tokenclient.Execute(tokenrequest);
var content = tokenresponse.Content;
RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
var des = deserial.Deserialize<AccessToken>(tokenresponse);
I am able to return the following JSON as a string:
{
"Access_Token": {
"Instance_Url": "https://url",
"Token": "StringToken",
"Expiration_date": "9/30/2015 6:15:27 PM",
"Refresh_Token": "StringToken"
}
}
However, when I pull des.Token, it returns a blank value. Can somebody kindly point out my error?

using Newtonsoft.Json;
var response = client.DownloadString(url + queryString);
ResponseModel<string> dataResponse = new ResponseModel<string>();
if (!string.IsNullOrEmpty(response))
{
dataResponse = JsonConvert.DeserializeObject<ResponseModel<string>>(response);
}

Related

Send post data to api in C#

I have this api in php that works ok when sending data from an html form.
<?php
include_once 'apiAppMovil.php';
$api = new AppMovil();
$error = '';
if(isset($_POST["nombre"]) && isset($_POST["ape"]) && isset($_POST["email"]) && isset($_POST["pass"])){
if($api->subirImagen($_FILES['foto'])){
$item = array(
"nombre" => $_POST["nombre"],
"ape" => $_POST["ape"],
"email" => $_POST["email"],
"pass" => $_POST["pass"],
"foto" => $api->getImagen() //Not used
);
$api->add($item);
}else{
$api->error('Error con el archivo: ' . $api->getError());
}
}
else{
$api->error('Error al llamar a la API');
}
?>
I want to send data but from c#. My class is the following:
public partial class Root
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
public partial class Item
{/*
[JsonProperty("id")]
[JsonConverter(typeof(ParseStringConverter))]
public long Id { get; set; }*/
[JsonProperty("nombre")]
public string Nombre { get; set; }
[JsonProperty("ape")]
public string Ape { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("pass")]
public string Pass { get; set; }
[JsonProperty("foto")] //Not Used
public string Foto { get; set; }
}
and my method is:
private async Task SignUpApiPost()
{
var data = new Item
{
Nombre = "Eric",
Ape = "Pino",
Pass = "M2022",
Email = "ericpinodiaz#gmail.com",
Foto = "default.jpeg" //Not Used
};
// Serialize our concrete class into a JSON String
var json = JsonConvert.SerializeObject(data);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
var httpClient = new HttpClient();
// Do the actual request and await the response
var response = await httpClient.PostAsync("https://app.domainexample.com/rest/add.php", httpContent);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//do thing
}
}
But I can't get the data to arrive, I have the errors "Error al llamar a la API" from Api php.
I think the problem is that var data = new Item{ is not declared correctly, can you help me and tell me where I am going wrong?
Thank you.
Edit:
I add the html with which it works correctly:
You should try something like the one below.
client.BaseAddress = new Uri("your url");
//HTTP POST
var postTask = client.PostAsJsonAsync<StudentViewModel>("your parameter name", Item);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
//do something
}

Cannot deserialize the current JSON object into type 'System.Collections.Generic.List1' in Xamarin Forms

I'm having an error in Xamarin Forms I tried to deserialize the object does anyone know What did I do wrong here?
This is my method
private async void GetEmployee()
{
var _token = await GetAccessToken();
//List<D365Employee> Employee = null;
using (var _clientD365 = new HttpClient())
{
var _uri = "domain here";
_client.BaseAddress = new Uri(_uri);
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
var _response = await _clientD365.GetAsync("my endpoint here");
var Emp = JsonConvert.DeserializeObject<List<Employee>>(_response.Content.ReadAsStringAsync().Result);
Employee = new ObservableCollection<Employee>(Emp);
}
}
This is my Model
public class Employee
{
[JsonProperty("#odata.etag")]
public string Context { get; set; }
public IList<EmployeeDetails> Value { get; set; }
}
public class EmployeeDetails
{
public string PersonnelNumber { get; set; }
public string EmploymentLegalEntityId { get; set; }
public string DimensionDisplayValue { get; set; }
}
This is the JSON I try to parse
{
"#odata.context": "https://employee.dynamics.com/data/$metadata#Employees(PersonnelNumber,EmploymentLegalEntityId,DimensionDisplayValue)",
"value": [
{
"#odata.etag": "W/\"JzEsNTYzNzE0NDYwMzsxNDg2NTk2NzY0LDU2MzcxNDc2OTM7MSw1NjM3MTQ0NjAzOzEsNTYzNzE0NDYwMzsxLDU2MzcxNDczNzE7MCwwOzAsMDsyNTY0OTEwODksNTYzwJw==\"",
"PersonnelNumber": "ID111028",
"EmploymentLegalEntityId": "OOP",
"DimensionDisplayValue": "----",
}
]
}
That JSON is a single object, not a list, so you need to deserialize it as a single object.
var Emp = JsonConvert.DeserializeObject<Employee>(await _response.Content.ReadAsStringAsync());

C# JSON - Error: Cannot initialize type with collection initializer (does not implement 'System.Collection.IEnumerable')

I have problem debug the below (in the simplest way possible...). I have a set of properties for a JSON, everything works up to the point that I try to serialize. I would appreciate the simplest way possible to correct, I have to use Newtonsoft.
Below the full C# code. The error area is being marked in comments.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace MY_TEST
{
public partial class headers
{
[JsonProperty("RequestID")]
public string myRequest { get; set; } = "someIDhere";
[JsonProperty("CorrelationID")]
public string CorrelationID { get; set; } = "1234567890";
[JsonProperty("Token")]
public string Token { get; set; } = "areallylongstringgoeshereastoken";
[JsonProperty("ContentType")]
public string Content_Type { get; set; } = "application/x-www-form-urlencoded";
}
public partial class access
{
[JsonProperty("allPs")]
public string allPs { get; set; } = "all";
[JsonProperty("availableAccounts")]
public string availableAccounts { get; set; } = "all";
}
public partial class body
{
[JsonProperty("combinedServiceIndicator")]
public bool combinedServiceIndicator { get; set; } = false;
[JsonProperty("frequencyPerDay")]
public int frequencyPerDay { get; set; } = 4;
[JsonProperty("recurringIndicator")]
public bool recurringIndicator { get; set; } = false;
[JsonProperty("validUntil")]
public string validUntil { get; set; } = "2020-12-31";
}
public class Consent //RootObject
{
[JsonProperty("headers")]
public headers headers { get; set; }
[JsonProperty("body")]
public body body { get; set; }
}
class Program
{
static HttpClient client = new HttpClient();
static void ShowConsent(Consent cust_some)
{
Console.WriteLine(cust_some.ToString());
}
static async Task<Uri> CreateConsentAsync(Consent cust_some)
{
HttpResponseMessage response = await client.PostAsJsonAsync("http://myurladdr:8001/me/and/you/api/", cust_some);
ShowConsent(cust_some);
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
static async Task<Consent> GetConsentAsync(string path)
{
Consent cust_some = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
cust_some = await response.Content.ReadAsAsync<Consent>();
}
return cust_some;
}
static void Main()
{
RunAsync().GetAwaiter().GetResult();
}
static async Task RunAsync()
{
client.BaseAddress = new Uri("http://myurladdr:8001/me/and/you/api/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// >---------- ERROR: Cannot initialize type 'Consent' with a collection initializer because it does not implement 'System.Collection.IEnumerable' ----------<
Consent cust_some = new Consent
{
// Headers
cust_some.headers.myRequest = "someIDhere",
cust_some.headers.CorrelationID = "1234567890",
cust_some.headers.Token = "areallylongstringgoeshereastoken"
cust_some.headers.Content_Type = "application/x-www-form-urlencoded",
// Body
cust_some.body.access.allPs = "all",
cust_some.body.access.availableAccounts = "all",
cust_some.body.combinedServiceIndicator = false,
cust_some.body.frequencyPerDay = 4,
cust_some.body.recurringIndicator = false,
cust_some.body.validUntil = "2020-12-31"
};
// >---------- ERROR ----------<
string json = JsonConvert.SerializeObject(cust_some, Formatting.Indented);
Console.WriteLine(json.ToString());
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine(json);
var url = await CreateConsentAsync(cust_some);
Console.WriteLine($"Created at {url}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}
Your'e using the identifier names inside their own initializer. For example, your'e using cust_some inside Consent initializer. You need to remove them, like so:
Consent cust_some = new Consent
{
// Headers
headers = new headers
{
myRequest = "someIDhere",
CorrelationID = "1234567890",
Token = "areallylongstringgoeshereastoken"
Content_Type = "application/x-www-form-urlencoded"
}
// Body
body = new body
{
access = new access
{
allPs = "all",
availableAccounts = "all"
}
combinedServiceIndicator = false,
frequencyPerDay = 4,
recurringIndicator = false,
validUntil = "2020-12-31"
};
}
Also, please note that per Microsoft naming conventions, all identifiers except parameter names should be capitalized, so e.g. headers, body, access and so on, both class and property names, should become Headers, Body, Access. You can read about it here.
In partial class body, add first before all the properties that are needed, the below:
[JsonProperty("access")]
public access access { get; internal set; }
Now, [kudos to user ***HeyJude**** - thank you!] create
Consent cust_some = new Consent
{
headers = new headers
{
myRequest = "someIDhere",
Correlation_ID = "1234567890",
Token = "areallylongstringgoeshereastoken",
Content_Type = "application/json" //"application/json; charset=utf-8"
},
body = new body
{
access = new access //this is how to include access in body
{
allPs = "allAccounts",
availableAccounts = "allAccounts"
},
combinedServiceIndicator = false,
frequencyPerDay = 4,
recurringIndicator = false,
validUntil = "2020-12-31"
}
};

C# HttpClient post content with FormUrlEncodedContent object in Dictionary string/object

I am trying to post a contect to my server.
This is how I have been doing it for the past and it was working until I had to use objects besides strings.
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authType, tokens);
var postParams = new Dictionary<string, object>();
postParams.Add("string", string);
postParams.Add("int", string);
postParams.Add("datetime", DateTime);
postParams.Add("datetime", DateTime);
postParams.Add("Match", Match);
postParams.Add("TicketId", token);
using (var postContent = new FormUrlEncodedContent(postParams.ToDictionary()))
{
var myContent = JsonConvert.SerializeObject(postParams);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (HttpResponseMessage response = await client.PostAsync(#"http://url/api", byteContent))
{
response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
var Json = JsonConvert.DeserializeObject<bool>(result);
return Json;
}
}
}
}
And this is how my request is supposed to be.
methode: POST
object: {
"title":"test-ticket-2",
"detail": "Description test create ticket in prod",
"dateStart": "2019-10-06",
"dateEnd": "2019-10-12",
"ratio": "2.15",
"matchResult": "2",
"matchs": [
{
"Teams": "Test-match-1",
"Proposal": "3x",
"DateStart": "2019-10-06 18:00",
"DateEnd": "2019-10-06 20:00",
"Payout": "0.6"
}
]
I have no idea IF and HOW I can add Objects other than string and make the request.
Any ideas?
Edit: Match looks like this
public class Match
{
public int Id { get; set; }
public string Teams { get; set; }
public string MatchResults { get; set; }
public string Proposal { get; set; }
public string Payout { get; set; }
public DateTime? DateStart { get; set; }
public DateTime? DateEnd { get; set; }
public Uri Ball { get; set; }
public int TicketId { get; set; }
}
HOW I can add Objects other than string and make the request. Any
ideas?
using (HttpClient httpclient = new HttpClient())
{
Models.ApplicationUser applicationUser = new ApplicationUser();
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(applicationUser);
StringContent stringContent = new StringContent(serialized);
httpclient.PostAsync("url", stringContent);
}
Hope you want to do something like this

Create webinar using citrix api in c#

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'

Categories