Restsharp getting especific JSON value from content - c#

I'm trying to get a specific value from my content, but I don't have any idea how I can do it.
I'm using RestSharp(C#) to run my JSON code, but when I execute the command it returns an error. I need to get the value from the property errorMessage.
var json = JsonConvert.SerializeObject(objectToUpdate);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddCookie("authToken", token);
request.AddParameter("application/json", json, ParameterType.RequestBody);
var response = client.Execute<T>(request);
After execute this code my response return the below JSON:
{
"response":{},
"status":{
"success":false,
"detail":{
"errormessage":[{
"fieldName":"departmentCode",
"errorMessage":"Department code provided is already associated with another department",
"errorCode":"DUPLICATE_DEPARTMENT_CODE"
}],
"error":"Validation failure on request",
"operation":"internal",
"errorcode":"412"
}
}
}

You could have a class, that represents the response you expect:
class ApiResponse{
// use a class that represents normal response instead of object
// if you need to interact with it.
public object Response {get; set;}
public ResponseStatus Status{get; set;}
}
class ResponseStatus {
public StatusDetail Detail{get; set;}
public bool Success {get; set;}
}
class StatusDetail {
public ErrorMessage[] ErrorMessage{get; set;}
}
class ErrorMessage{
public string FieldName{get; set;}
public string ErrorMessage{get; set;}
public string ErrorCode{get; set;}
}
Then you have that, you can get parsed response from RestSharp client:
var response = client.Execute<ApiResponse>(request);
var message = response.Data.Response.Detail.ErrorMessage.First().ErrorMessage;
According to RestSharp docs, they recomment using response classes over dynamic objects (https://github.com/restsharp/RestSharp/wiki/Recommended-Usage).

Related

Converting a JSON into own type results in null objects

from my rest call, I am receiving this JSON:
{
"livemode": true,
"error": {
"type": "unauthorized",
"message": "You did not provide a valid API key."
}
}
I need to fetch type and message into my type:
public class TestObject
{
string type { get; set; }
string message { get; set; }
}
But this returns null objects:
HttpClient client = new HttpClient();
Uri uri = new Uri("https://api.onlinebetaalplatform.nl/v1");
HttpResponseMessage response = await client.GetAsync(uri);
string content = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(content);
TestObject album = json.ToObject<TestObject>();
1.) I understand that the type and message attributes are "nested". How do I access them?
2.) Even if I call my type livemode and error, the objects still return null.
Can you help me out a little?
Thank you :)
There seems to be one set of curly brackets to many. I am pretty sure that the api you are querying is not returning the first and the last curly bracket. Continue on after that has been taken care of.
In order to fetch the data, add these class definitions
public class Error
{
public string type { get; set; }
public string message { get; set; }
}
public class Root
{
public bool livemode { get; set; }
public Error error { get; set; }
}
and change
TestObject album = json.ToObject<TestObject>();
To
Root album = json.ToObject<Root>();
As some of the comments to your question mentioned, you are currently trying to convert the JSON string to the nested Error object instead of the root object, where the Error object is located.
In the future, there are tools that can generate C# classes from JSON. I used https://json2csharp.com/ this time around to do so.
EDIT:
I just found out that Visual Studio actually has an in-built JSON to Class feature!

Cannot deserialize RestResponse with RestSharp C#

I am trying to deserialize JSON to C# object but not able to get rid of this compiler error. Any help would be much appreciated.
JSON
{
AX:{BX:1777}
}
Here are my deserializer classes:
Response.cs
{
public class Response
{
public AX Ax { get; set; }
}
}
AX.cs
{
public class AX
{
public long Bx { get; set; }
}
}
Here is the line that is problematic:
IRestResponse<Response> response = client.Execute<Response>(request);
response.Content is just as fine and returns the raw JSON but I want it to be an instance of the Response class. I want to access Bx like this:
var price = response.Ax.Bx; // should return 1777
But this line produces the following compiler error:
Error: IRestResponse does not contain definition for 'Ax'
For what it's worth, and having spent some time searching around this, I would have used Newtonsoft.Json and solved it like this:
IRestResponse response = client.Execute(request);
string ResponseStr = response.Content.ToString();
dynamic Response = JsonConvert.DeserializeObject<dynamic>(ResponseStr);
you can then call off the elements as you need them:
var price = Response.AX.BX;
string Description = Response.AX.Desc.ToString(); etc
Hope this helps someone
Problem is with case sensitive. RestSharp serializer expects following json structure
{
Ax:{Bx:1777}
}
You have 3 ways to deal with it:
1) add DataContract and DataMember to your classes
[DataContract]
public class Response
{
[DataMember(Name = "AX")]
public AX Ax { get; set; }
}
[DataContract]
public class AX
{
[DataMember(Name = "BX")]
public long Bx { get; set; }
}
2) write your own serializer that ignores case sensitive and use it with restsharp
3) change your json structure

youtube api in c# code

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com/youtube/v3/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("search?q=manam&type=video&order=relevance&part=snippet&maxResults=50&key=AIzaSyA4GZFAgfvsAItwFRmnAZvbTHoDeyunf2k").Result;
if (response.IsSuccessStatusCode)
{
dynamic lists = await response.Content.ReadAsAsync<mycustomObject>(); // what should I write here
}
}
I am trying to get the youtube videos with web api call in my project.
This is the code what I tried till now,
to get the response what should I use in the place of myCustomObject ?
when I am trying with the above url in browser I am getting the data, when I ran above code it return null,
Anything wrong with above code?
I just want to get the data from this method,
Any help will be greatly appreciated.
You need a class which represents the JSON data being returned from the call.
If you call your GET request in a browser you'll see the JSON response looks something like this:
{
kind: "youtube#searchListResponse"
etag: ""tbWC5XrSXxe1WOAx6MK9z4hHSU8/lh-waoy9ByBY2eB-oZs7niK51FU""
nextPageToken: "CDIQAA"
pageInfo:
{
totalResults: 176872
resultsPerPage: 50
}-
items: [...50]-
}
So you need to create a class with matching fields which the deserialize command will then populate for you. Something like this:
public class YoutubeApiResponse()
{
public string kind {get; set;}
public string etag {get; set;}
public string nextPageToken {get; set;}
public PageInfo pageInfo {get; set;}
public List<Item> items {get; set;}
}
And call like this:
var youtubeResponse = await response.Content.ReadAsAsync<YoutubeApiResponse().Result();
I'd recommend looking at the .Net Client Library - it will take care of a lot of this stuff for you.

How to correctly deserialise JSONArrays using RestSharp

How do I correctly deserialise the results of this call (you can click to see output):
https://bitpay.com/api/rates
I'm using a POCO object like this:
public class BitpayPrice
{
public string code { get; set; }
public string name { get; set; }
public double rate { get; set; }
}
And I'm calling the API like so:
var client = new RestClient();
client.BaseUrl = "https://bitpay.com";
var request = new RestRequest("/api/rates", Method.GET);
var response = client.Execute<BitpayPrice[]>(request);
Now, I know that the call to execute is wrong, but how do I un-wrongify it? I'd like to get back an array of BitcoinPrice objects.
RestSharp doesn't support deserializing into array, the best you can get is a List<>:
var response = client.Execute<List<BitpayPrice>>(request);
The reason is that types that you can deserialize to are required to have public parameterless constructor (for performance reasons mostly).

RestSharp: Converting results

I get the following JSON that I am trying to convert to a business object using RestSharp
{
"valid":true,
"data":[
{
"dealerId":"4373",
"branchId":"4373",
}
]
}
I wish to convert to:
public class Dealer
{
public string dealerId ;
public string branchId;
}
But this fails, though the JSON is fine:
var client = new RestClient("http://www.????.com.au");
var request = new RestRequest(string.Format("service/autocomplete/dealer/{0}/{1}.json", suburb.PostCode, suburb.City.Trim().Replace(" ", "%20")), Method.GET);
var response2 = client.Execute<Dealer>(request);
return response2.Data;
Your business object doesn't match the response JSON you are getting back. If you want your response to serialize, your C# object would look something like
public class DealerResponse
{
public bool valid { get;set; }
List<Dealer> data { get;set; }
}
public class Dealer
{
public string dealerId;
public string branchId;
}
I haven't tested this code, but even though you are only interested in the information in 'data', your response C# objects still need to represent the whole JSON response to serialize correctly.
Hope that helps.

Categories