Pass response data from RestSharp to JSON Properties - c#

I am new to API, RestSharp and JSON. I got the Response Data from the API, my problem is I didn't know how to pass the response data to JSON Properties that I've been readied.
Here is my Code.
This is the API response I received.
{
"data": {
"id": "link_4txtnKwrBbTTQfRwswSLcinw",
"type": "link",
"attributes": {
"amount": 65656,
"archived": false,
"currency": "USD",
"description": "2323",
"livemode": false,
"fee": 0,
"remarks": "12321",
"status": "unpaid",
"tax_amount": null,
"taxes": [],
"checkout_url": "https://pm.link/------",
"reference_number": "sadXlwd",
"created_at": 1670820915,
"updated_at": 1670820915,
"payments": []
}
}
}
RestSharp Code:
private void GenerateLink(double amount, string description, string remarks)
{
var client = new RestClient("https://api.paymongo.com/v1/links");
var request = new RestRequest("", Method.Post);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Basic c2tfdGVzdF9aMXdma2tUaDdaUUNjR25oNnlOYUpQZks6c2tfdGVzdF9aMXdma2tUaDdaUUNjR25oNnlOYUpQZks=");
request.AddParameter("application/json", "{\"data\":{\"attributes\":{\"amount\":" + amount + ",\"description\":\"" + description + "\",\"remarks\":\"" + remarks + "\"}}}", ParameterType.RequestBody);
RestResponse response = client.Execute(request);
Console.WriteLine(response.StatusCode);
if(response.IsSuccessStatusCode)
{
}
}
private void BtnPay_Click(object sender, EventArgs e)
{
amount = 20000;
description = "JC DIAZ";
remarks = "Delivery Date : " + dateTimePicker1.Value.ToString("MMM dd, yyyy");
GenerateLink(amount, description, remarks);
}
The variables that I want to fill with RestSharp Response Contents
public partial class Attributes
{
[JsonProperty("amount")]
public int Amount = 0;
[JsonProperty("archived")]
public bool Archived = false;
[JsonProperty("currency")]
public string Currency = "";
[JsonProperty("description")]
public string Description = "";
[JsonProperty("livemode")]
public bool Livemode = false;
[JsonProperty("fee")]
public int Fee = 0;
[JsonProperty("remarks")]
public string Remarks = "";
[JsonProperty("status")]
public string Status = "";
[JsonProperty("tax_amount")]
public object TaxAmount = "";
[JsonProperty("taxes")]
public List<object> Taxes = null;
[JsonProperty("checkout_url")]
public string CheckoutUrl = "";
[JsonProperty("reference_number")]
public string ReferenceNumber = "";
[JsonProperty("created_at")]
public int CreatedAt = 0;
[JsonProperty("updated_at")]
public int UpdatedAt = 0;
[JsonProperty("payments")]
public List<object> Payments = null;
}
public partial class Data
{
[JsonProperty("id")]
public string Id = "";
[JsonProperty("type")]
public string Type = "";
[JsonProperty("attributes")]
public Attributes Attributes = null;
}
public partial class Model
{
[JsonProperty("data")]
public Data Data = null;
}
I tried this code, but it still returns no results.
var model = JsonConvert.DeserializeObject<Attributes>(response.Content);
string value = model.CheckoutUrl;
I expect to populate the attributes class with the contents of RestResponse.

you will have to create a root class and use it to deserialize your json
Model model = JsonConvert.DeserializeObject<Model>(response.Content);
string value = model.Data.Attributes.CheckoutUrl;
public partial class Model
{
[JsonProperty("data")]
public Data data { get; set; }
}
public partial class Data
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("attributes")]
public Attributes Attributes { get; set; }
}
or if you only need attributes data, you can do it without the extra classes
Attributes attributes = JObject.Parse(response.Content)["Data"]["Attributes"].ToObject<Attributes>();
string checkoutUrl = attributes.CheckoutUrl;

Related

How to Deserialize json Object on gridview?

I am building C# windows form that accessing json data. I want to make it display on gridview.
How can I DeserializeObject the json data on gridview?
Sorry for newbie here.
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public IList<Namedata> namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
string username = "myuser";
string password = "myuserpass";
byte[] byteArray = Encoding.UTF8.GetBytes("{\"name\":\"" + Name.Text + "\",\"id\":\"1\"}");
WebRequest request = WebRequest.Create("http://myservice/Service4.svc/s_name");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)));
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream = request.GetResponse().GetResponseStream();
var result = (new StreamReader(stream).ReadLine());
JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = result;
}
here are json data:
{
"s_name": {
"ResultCode": 1,
"ResultName": "Found",
"namedatas": [
{
"PeopleName": "Jane",
"PeopleAge": "20",
"PeopleSurname": "Jade"
},
{
"PeopleName": "Newton",
"PeopleAge": "18",
"PeopleSurname": "Handy"
},
{
"PeopleName": "Java",
"PeopleAge": "21",
"PeopleSurname": "Handy"
}
]
}
}
You are not giving the gridview the correct source. Try this,
var data = JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = data.s_name.namedatas;
Base on the information, here is a potential solution:
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public Namedata[] namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
HttpClient _client = new HttpClient();
string username = "myuser";
string password = "myuserpass";
var byteArray = System.Text.Encoding.ASCII.GetBytes($"{username}:{password}");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
dynamic content = new ExpandoObject();
content.name = Name.Text;
content.id = 1;
var json = Newtonsoft.Json.JsonConvert.SerializeObject(content);
var data = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = _client.PostAsync("http://myservice/Service4.svc/s_name", data).Result;
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(response.Content.ReadAsStringAsync().Result);
ultragridiew1.DataSource = data.s_name.namedatas;
}
Main change I have done is to use HttpClient. It removes a lot of boilerplate code that is required with webrequest.
#Chetan Ranpariya had correct me. Thank you
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public IList<Namedata> namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
string username = "myuser";
string password = "myuserpass";
byte[] byteArray = Encoding.UTF8.GetBytes("{\"name\":\"" + Name.Text + "\",\"id\":\"1\"}");
WebRequest request = WebRequest.Create("http://myservice/Service4.svc/s_name");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)));
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream = request.GetResponse().GetResponseStream();
var result = (new StreamReader(stream).ReadLine());
var exampleObj = JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = exampleObj.s_name.namedatas
}

Json deserialize says children could not evaluate- xamarin.forms

I have xamarin.forms app in which I am trying to consume an API. I can get the results but cant deserialize the data. It says "Childern could not be evaluated"
My Json data
{
"success": true,
"user": {
"auth_uuid": "52320",
"current_store": 9,
"permissions": {
"write_notifications": true,
},
"has_accepted_mobile_one_terms": false,
"store": {
"id": 9,
"name": "South Street",
"number": "0009",
}
},
"message": "User Logged In",
"sidebarItems": [
{
"id": 53,
"name": "Notification Center",
}
],
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
}
My Corresponding C# class
public clas loginData
{
public class Permissions
{
public bool write_notifications { get; set; }
}
public class Store
{
public int id { get; set; }
public string name { get; set; }
public string number { get; set; }
}
public class User
{
public string auth_uuid { get; set; }
public int current_store { get; set; }
public Permissions permissions { get; set; }
public bool has_accepted_mobile_one_terms { get; set; }
public Store store { get; set; }
}
public class SidebarItem
{
public int id { get; set; }
public string name { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public User user { get; set; }
public string message { get; set; }
public List<SidebarItem> sidebarItems { get; set; }
public string token { get; set; }
}
}
My common class for making API call
public class APICall
{
Uri baseAddress = new Uri(CommonValues.BaseURL);
string apiurl;
string postdata;
public ErrorMessageData errorMessage;
public APICall(string apiurl, string postdata)
{
this.apiurl = apiurl;
this.postdata = postdata;
this.loadingIndicator = loadingIndicator;
errorMessage = null;
}
public T APICallResult<T>()
{
try
{
var client = new HttpClient { BaseAddress = baseAddress };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var req = new HttpRequestMessage(HttpMethod.Post, apiurl);
req.Content = new StringContent(postdata, Encoding.UTF8, "application/json");
string stringObtained = "";
Task<string> task = Task.Run(async () => await Threading(client, req));
task.Wait();
stringObtained = task.Result;
var jsonObtained = Regex.Unescape(stringObtained);
var resultJSON = '[' + jsonObtained + ']';
T resultObject;//Generic type object
try
{
resultObject = JsonConvert.DeserializeObject<T>(resultJSON);
return resultObject;
}
catch (Exception)
{
List<ErrorMessageData> errorMessages = JsonConvert.DeserializeObject<List<ErrorMessageData>>(resultJSON);
errorMessage = errorMessages[0];
return default(T);
}
}
catch (Exception e)
{
errorMessage = new ErrorMessageData();
errorMessage.Flag = false;
errorMessage.Message = e.Message;
return default(T);
}
}
async Task<string> Threading(HttpClient client, HttpRequestMessage req)
{
var resp = await client.SendAsync(req);
resp.EnsureSuccessStatusCode();
string stringObtained = await resp.Content.ReadAsStringAsync();
return stringObtained;
}
}
How I am making API call
ObservableCollection<loginData> AuthDataObj;
string postdataForAuth = "{\"email\":\"" + "sample#sam.com" + "\",\"password\":\"" + "1234" + "\"}";
NCAPICall callForAuth = new APICall("/auth/login", postdataForAuth, null);
try
{
AuthDataObj = callForAuth.APICallResult<ObservableCollection<loginData>>();
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.Message, "ok");
}
How to solve this issue? Is this something related to mapping of data to my model class?Any help is appriciated.
You need to use RootObject for the deserialization.
Change this line of code
var AuthDataObj = callForAuth.APICallResult<ObservableCollection<RootObject>>();

C# - Instance a class that returns JSON objects

I am learning C# and I made a console application that reads a text entry and searches an API that returns a value in JSON, then I show these values by console.
Now I need to pass this to a graphical environment and what I have done is create a class "MyClass" and within that class I have created a method "MyMethod" that will receive as a parameter a 15 digit number and will query the API (such as the console application did) and then return those values.
What I do not know is how to create the method correctly and how to instantiate it from another class because it generates errors.
My JSON:
{
"success": true,
"result": {
"id": "20429683581",
"name": "CINEPLEX S.A",
"Condition": "HABIDO",
"PLE": "02\/01\/2013",
"lawyers": [
{
"type": "DNI",
"numdoc": "07871885",
"name": "PONCE PINTO ALEJANDRO EDUARDO",
"date": "22\/08\/2000"
},
{
"type": "DNI",
"numdoc": "09333203",
"name": "SORIANO BARRANTES JOSE FERNANDO",
"date": "22\/09\/2008"
}
],
"workers": [
{
"time": "2017-07",
"service": "8"
},
{
"time": "2018-06",
"service": "13"
}
]
}
}
I have these defined classes:
public class Lawyer
{
public string type { get; set; }
public string numdoc { get; set; }
public string name { get; set; }
public string date { get; set; }
}
public class Worker
{
public string time { get; set; }
public string service { get; set; }
}
public class Result
{
public string id { get; set; }
public string name { get; set; }
public string Condition { get; set; }
public string PLE { get; set; }
public List<Lawyer> lawyers { get; set; }
public List<Worker> workers { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public Result result { get; set; }
}
In a console application they worked well:
RootObject rootobject;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://www.example.com/api/?get=" + inid);
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
{
var json = reader.ReadToEnd();
rootobject = JsonConvert.DeserializeObject<RootObject>(json);
}
if (rootobject.success == true)
{
Console.WriteLine("---------------");
Console.WriteLine("ID: " + rootobject.result.id);
Console.WriteLine("NAME: " + rootobject.result.name);
Console.WriteLine("CONDITION: " + rootobject.result.Condition);
Console.WriteLine("PLE: " + rootobject.result.PLE);
}
else
{
Console.WriteLine("---------------");
Console.WriteLine("NOTHING");
}
}
catch (Exception)
{
Console.WriteLine("---------------");
Console.WriteLine("ERROR");
}
I have since migrated to a GUI based application using MyClass:
class MyClass
{
public void MyMethod(int inRUC){
RootObject rootobject;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://www.example.com/api/?get=" + inRUC);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
{
var json = reader.ReadToEnd();
rootobject = JsonConvert.DeserializeObject<RootObject>(json);
}
}
}
Now I want to get the value of a text entry in the graphic form and instantiate the class to get the results and print them in the text fields of the same form, but I do not know how to instantiate it correctly and how to place the values correctly, this is what I am currently trying: (txtRuc1) is my input of my form and EditText1 is my output of my form:
private void Button1_ClickBefore(object sboObject, SAPbouiCOM.SBOItemEventArg pVal, out bool BubbleEvent)
{
if (string.IsNullOrEmpty(txtRuc1.Value.ToString()))
{
BubbleEvent = false;
}
else
{
//Ok, I known that it is wrong
BubbleEvent = true;
MyClass obj = new Sunat();
EditText1.Value = obj.MyMethod(txtRuc1.value).rootobject.result.name;
}
}
What would be the correct form? Visual studio returns the error: Cannot convert "string" to "int" in these line:
obj.MyMethod(txtRuc1.value).rootobject.result.name
first, your MyMethod need to return RootObject instead of void
public RootObject MyMethod(int inRUC){
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://www.example.com/api/?get=" + inRUC);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
{
var json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<RootObject>(json);
}
}
then the error was caused by txtRuc1.value might string value but the MyMethod method needs int.
so you can try to use int.TryParse method to parse the input value to int the pass it.
int para = 0;
int.TryParse(txtRuc1.value,out para);
EditText1.Value = obj.MyMethod(para).rootobject.result.name;

How do I deserialize my JSON?

What would be my next step to take? I want to be able to write the block with the id value of ex 1. Or the block with ex GPIO value 3 with something simple as maybe WriteLine(id1) Relay.cs
public class Relay
{
public int GPIO { get; set; }
public int id { get; set; }
public int status { get; set; }
public string type { get; set; }
}
Program.cs
static void Main(string[] args)
{
var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
var request = new RestRequest("relays", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Execute<Relay>(request);
Console.WriteLine(response.Content);
Console.ReadLine();
}
and my array on 192.168.0.3:1337/auto/api/v1.0/relays
{
"relays": [
{
"GPIO": 2,
"id": 1,
"status": 0,
"type": "Relay"
},
{
"GPIO": 3,
"id": 2,
"status": 0,
"type": "Relay"
}
]
}
I'm sorry if anything is unclear, or if the answer is simple. If I missed to include something important, just point it out and I'll post it!
you can deserialize it in List of Relay and iterate and read any value you want
static void Main(string[] args)
{
var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
var request = new RestRequest("relays", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Execute<Relay>(request);
JavaScriptSerializer ser = new JavaScriptSerializer();
var relayList = ser.Deserialize<List<Relay>>(response.Content);
foreach(Relay relay in relayList)
Console.WriteLine(relay.ID);
Console.ReadLine();
}
You need to parse that JSON into objects to manipulate them, and it seems that your REST client already does it, just need to pass the correct type.
1-Create the class structure like the structure you're receiving:
public class Relay
{
public int GPIO { get; set; }
public int id { get; set; }
public int status { get; set; }
public string type { get; set; }
}
public class RelayCollection
{
public Relay[] relays { get; set; }
}
2-Parse the received json:
var relayCollection = client.Execute<RelayCollection>(request);
Now you have all the relays inside relayCollection.relays, manipulate them as any other array/class
Beforehand I apologize for my English, but you can serialize a json by creating a list of your class and then deserialize the json like this:
public class Relay {
int GPIO;
public int gPIO {get {return GPIO;} set {GPIO=value;}}
int Id;
public int ID {get {return Id;} set {Id = value;}}
int Status;
public int status {get {return Status;} set {Status = value;}}
string Type;
public string type {get {return Type;} set {Type = value;}}
}
Now create a class list
List<Relay > relayList = new List<Relay >();
And finally deserealize the json
relayList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Relay>>(request);

Can't deserialize JSON to list in C#. No integer (0-n) indexes

How can I deserialize JSON to a list using DeserializeObject and JsonProperty while the indexes of the elements are non-integer?
JSON:
{
"success": true,
"TEST": {
"360450323_188530139": {
"id": "24216",
"name": "zxc",
"desc": "cxz"
},
"310777518_0": {
"id": "6458678634",
"name": "dfgsfd",
"desc": "sdfxcvnbhr"
}
}
}
Is there any way to make a list from that?
I've tried:
using(WebClient wc = new WebClient())
{
var url = "...";
var json = wc.DownloadString(url);
Result result = JsonConvert.DeserializeObject<Result>(json);
}
public class Result
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("TEST")]
public List<Test> Tests{ get; set; }
}
public class Test
{
[JsonProperty("id")]
public int id { get; set;}
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("desc")]
public string Desc { get; set; }
}
You have a keyed collection in the JSON, which maps easily to a dictionary. You could examine result.Test.Values
using(WebClient wc = new WebClient())
{
var url = "...";
var json = wc.DownloadString(url);
Result result = JsonConvert.DeserializeObject<Result>(json);
// result.Values should contain the Test instances at this point.
}
public class Result
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("TEST")]
public Dictionary<string,Test> Tests{ get; set; }
}
public class Test
{
// omitted - same as in question.
}

Categories

Resources