I need to get GET response from REST API. I use RestSharp. The problem is, that one name of the response attribute is "$". This is the response:
[
{
"CodeId": {
"$": "00000000"
},
"Entity": {
"LegalName": {
"#xml:lang": "cs",
"$": "xxxxx"
}
}
}
]
How should I use the RestSharp to get the value of Entity.LegalName.$ ?
I found the answer thanks by #fredrik.
var client = new RestClient(url);
var request = new RestRequest(urlRequest, DataFormat.Json);
var response = client.Get(request);
Console.WriteLine(JsonSerializer.Deserialize<List<TestRestResponseTemplate>>(response.Content)[0].Entity.LegalName.Value);
TestRestResponseTemplate:
public class TestRestResponseTemplate
{
public Entity Entity { get; set; }
}
public class LegalName
{
[JsonPropertyName("#xml:lang")]
public string Language { get; set; }
[JsonPropertyName("$")]
public string Value { get; set; }
}
public class Entity
{
public LegalName LegalName { get; set; }
}
Related
I'm getting a post request to my api (x-www-form-urlencoded) and the body of the request looks like this:
worker=%7B%22_id%22%3A+%7B%22%24oid%22%3A+%2261asd23e9231241dfd2b4c3bd%22%7D%2C+%22sid%22%3A+%22WKb32df49cas43413585352e8a6e2%cd%22%22%%22%3A+1234154123%7D%7D&task=%7B%22_id%22%3A+%7B%22%24oid%22%3A+%2261caffc34dsf33182b4c789
continues.
There are 2 objects (classes) that I need to receive in this incoming request, and I created the class structure of these 2 objects: For example, my class structure is as follows:
public class Worker
{
[JsonProperty("friendly_name")]
public string FriendlyName { get; set; }
[JsonProperty("date_updated")]
public WorkerDateUpdated DateUpdated { get; set; }
[JsonProperty("activity")]
public string Activity { get; set; }
[JsonProperty("workspace_sid")]
public string WorkspaceSid { get; set; }
[JsonProperty("date_created")]
public WorkerDateCreated DateCreated { get; set; }
[JsonProperty("queues")]
public List<string> queues { get; set; }
}
public class Task
{
[JsonProperty("reason")]
public string Reason { get; set; }
[JsonProperty("date_updated")]
public TaskDateUpdated DateUpdated { get; }
[JsonProperty("assignment_status")]
public string AssignmentStatus { get; set; }
[JsonProperty("total_cost")]
public TaskTotalCost TotalCost { get; set; }
}
In the incoming request, I receive 3 objects (class) as url-encoded, I only need 2 objects and their properties.
using (var reader = new StreamReader(
HttpContext.Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false
))
{
var bodyString = await reader.ReadToEndAsync();
_logger.LogInformation("BodyString ---> " + bodyString);
var decodedUrl = HttpUtility.UrlDecode(bodyString);
_logger.LogInformation(" decodedUrl ---> " + decodedUrl);
}
I can read the incoming body and convert it to decoded format. Below is an example:
worker={"_id": {"$oid": "XXXXXXXXXX"}, "sid": "XXXXXXXXXXXXX", "x": true, "account_sid": "XXXXXXXXXXXX", "workspace_sid": "XXXXXXXXXXXX", "queues ": ["XXXXXXXXXXXXXX"], "activity": "idle", "available": true, "friendly_name": "XXXXXXXX", "attributes": {"mail": "XXXXXXXXXXXX", "name": "XXXXXXXXXX" }, "date_created": {"$date": XXXXXXXXX}, "date_updated": {"$date": XXXXXXXXXX}, "date_status_changed": {"$date": XXXXXXXXXXXXX}}&task={"_id": {" $oid": "XXXXXXXXXXXXXX"}, "sid": "XXXXXXXXXXXX", "x": true, "account_sid": "XXXXXXXXXXX", "workspace_sid": "XXXXXXXXXXXXXXXXXX", "workflow_sid": "XXXXXXXXXXXX", "workflow_friendly_name" : "daytime1", "initial_attributes": {"station_name": "XXXXX", "component_type": X, "component_id": XXX, "mail": "XXXXXX", "main_issue": "XXXXXXXXXXXXXX", "predictivi_maintenance_time": "XXXXXXXXXX", "hospital_name": "\u00dcsk\u00fcdar XXXXXXXXXXX"}
I can see it as , but I can't deserialize it. Or I don't know if I'm doing it wrong. I have created a separate class that contains my 2 classes. I keep my Worker and Task class in it, I cannot deserialize to that class, it does not deserialize in any way. Unexpected charachter throws exception. How can I convert these objects to json format or object format?
Edit:
My Other Custom classes:
public class TaskDateUpdated
{
[JsonProperty("$date")]
public long Date { get; set; }
}
public class TaskTotalCost
{
[JsonProperty("$numberDecimal")]
public string NumberDecimal { get; set; }
}
public class TaskDateCreated
{
[JsonProperty("$date")]
public long Date { get; set; }
}
public class TaskLastChargeDate
{
[JsonProperty("$date")]
public long Date { get; set; }
}
public class TaskId
{
[JsonProperty("$oid")]
public string Oid { get; set; }
}
public class WorkerDateUpdated
{
[JsonProperty("$date")]
public long date { get; set; }
}
public class WorkerDateCreated
{
[JsonProperty("$date")]
public long date { get; set; }
}
public class WorkerDateStatusChanged
{
[JsonProperty("$date")]
public long date { get; set; }
}
I also have a single class containing these 2 classes, I get an error when I try to deserialize to this class, I also get an error when I try to deserialize it to other worker and task classes separately. I can't deserialize at all.
public class DataContainer
{
public Task Task { get; set; }
public Worker Worker { get; set; }
}
My post method looks like this:
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
{
using (var reader = new StreamReader(
HttpContext.Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false
))
{
var bodyString = await reader.ReadToEndAsync();
_logger.LogInformation("BodyString ---> " + bodyString);
var decoded = HttpUtility.UrlDecode(bodyString);
//here is where i need to deserialize and convert it to
//a valid json and object
}
}
You can use HttpUtility.ParseQueryString to parse it into a NameValueCollection, then simply use the indexer ["worker"] on that.
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
{
using (var reader = new StreamReader(
HttpContext.Request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false
))
{
var bodyString = await reader.ReadToEndAsync();
var decoded = HttpUtility.ParseQueryString(bodyString);
var worker = JsonSerializer.Deserialize<Worker>(decoded["worker"]);
var task = JsonSerializer.Deserialize<Task>(decoded["task"]);
// or whatever your JSON deserializer is
}
}
In newer versions of ASP.net Core you can use HttpContext.Request.Form
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public async Task<ActionResult<ResponseRequest>> AddWorkerTask()
{
var worker = JsonSerializer.Deserialize<Worker>(HttpContext.Request.Form["worker"]);
var task = JsonSerializer.Deserialize<Task>(HttpContext.Request.Form["task"]); // or whatever your JSON deserializer is
}
I'm using the last GraphQL client NuGet package (3.2.1) on .NET Core 3.1 project and calling a GraphQL API.
When I do the "SendQueryAsync()" or "SendMutationAsync()" the response status code is OK but the Data property is always Null.
I think it's related to the serialization but idk where is the problem.
How I use it
var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions { EndPoint = new Uri(_graphQLEndPoint) }, new NewtonsoftJsonSerializer(), httpclient);
var request = new GraphQLRequest
{
Query = #"query CurrentUserCards {
currentUser {
cardsCount
cards {
name
pictureUrl
position
player {
displayName
}
}
}
}"
};
var data = await graphQLClient.SendQueryAsync<Data>(request);
Even if I put "Rootobject" class it's null.
My model
I generated my model with "Paste JSON as classes" feature on Visual studio, from the JSON result.
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public Currentuser currentUser { get; set; }
}
public class Currentuser
{
public int cardsCount { get; set; }
public Card[] cards { get; set; }
}
public class Card
{
public string name { get; set; }
public string pictureUrl { get; set; }
public string position { get; set; }
public Player player { get; set; }
}
public class Player
{
public string displayName { get; set; }
}
Response from Postman
{
"data": {
"currentUser": {
"cardsCount": 12,
"cards": [
{
"name": "Henry",
"pictureUrl": "",
"position": "Coach",
"player": {
"displayName": "Thierry Henry",
}
},
{
"name": "Zidane",
"pictureUrl": "",
"position": "Coach",
"player": {
"displayName": "Zinedine Zidane",
}
}
...
]
}
}
}
I have solved this by removing the Rootobject class and use the Data class as root. I think that the response always has a data property so it skips that in the deserialization.
I am connecting to an API, but not having any luck retrieving the data in Json. I have different endpoints to use, but cant seem the any to work. I believe /products should give me the entire list but am having no luck.
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
//go get the data
string token = "auth token";
client.BaseAddress = new Uri("");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Console.WriteLine("GET");
HttpResponseMessage response = await client.GetAsync("/products/6");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Connected");
RootObject product = await response.Content.ReadAsAsync<RootObject>();
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", product.data.id,product.data.name,product.data.sort,product.data.designation_id,product.data.designation_id);
}
else
{
Console.WriteLine("Failed");
Console.WriteLine(response.Headers);
}
}
}
}
The response I am getting in the console on this is:
0
1/1/0001 12:00:00 AM
1/1/0001 12:00:00 AM
Product class:
public class RootObject
{
public Product data { get; set; }
}
public class Product
{
public int id { get; set; }
public object designation_id { get; set; }
public string name { get; set; }
public object alternate_name { get; set; }
public object description { get; set; }
public int sort { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
The response I get when testing connection with postman is as follows:
{
"data": {
"id": 6,
"designation_id": null,
"name": "Multirate Fork Springs Kit",
"alternate_name": null,
"description": null,
"sort": 0,
"created_at": "2016-06-17 20:47:51",
"updated_at": "2018-05-25 09:40:50"
}
}
nuget Newtonsoft.Json
and you can do something like this:
using Newtonsoft.Json;
in client, using response
Product product = JsonConvert.DeserializeObject<Product>(your response string);
this works really well, as long as your product class has all the right attributes you should be good to go!
I want to send Post Request with C# WebClient with this Json Schema :
[
{
"id": "00000000-0000-0000-0000-000000000000",
"points": [
{
"timestamp": "2017-12-04T16:07:44.562Z",
"value": 0
}
]
}
]
I've tried This :
public class RequestData
{
public string id {get; set; }
public points points { get; set; }
}
public class points
{
public DateTime timestamp { get; set; }
public float value { get; set; }
}
My Program :
Random number = new Random();
var req = new RequestData();
req.id = "0e13d9c-571c-44f4-b796-7c40c0e20a1d";
req.points = new points { timestamp = DateTime.UtcNow, value =
number.Next(100, 99999) };
JsonSerializerSettings settings = new JsonSerializerSettings();
var data = JsonConvert.SerializeObject(req);
WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.Authorization,
AquaAtuhorization.accessToken);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString ("http://localhost:8080/api/v1/data/writeNumericValues",
data );
And I always get Http 415 (Unsupported Media Type).
How could I format my C# Object as the restApi accepeted Format.
Look at the JSON, the square brackets [ ] denote that something is an array. In this case both RequestData and points have to be an array, see the example below:
public class RequestData
{
public string id { get; set; }
public List<points> points { get; set; } // I use list, could be an array
}
public class points
{
public DateTime timestamp { get; set; }
public float value { get; set; }
}
Then construct your req object like this:
var req = new List<RequestData> // Again I use list, could be an array
{
new RequestData
{
id = "0e740d9c-571c-44f4-b796-7c40c0e20a1d",
points = new List<points> // Defined as a list, even though it has one entry
{
new points
{
timestamp = DateTime.UtcNow,
value = number.Next(100, 99999)
}
}
}
};
Then just serialize it as normal, the result will be the below:
[
{
"id":"0e740d9c-571c-44f4-b796-7c40c0e20a1d",
"points":[
{
"timestamp":"2017-12-04T17:12:25.8957648Z",
"value":59522.0
}
]
}
]
Your Json class needs to be like this, see http://json2csharp.com/ or use paste as JSON from VS https://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/
public class Point
{
public DateTime timestamp { get; set; }
public int value { get; set; }
}
public class RootObject
{
public string id { get; set; }
public List<Point> points { get; set; }
}`
I am trying to get a field from the response from the rest services in the Web API we are building. The JSON looks like this:
{
"d": {
"results": [{
"__metadata": {
"id": "Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)",
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)",
"etag": "\"6\"",
"type": "SP.Data.St_x0020_CdsListItem"
},
"Folder": {
"__deferred": {
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)/Folder"
}
},
"ParentList": {
"__deferred": {
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)/ParentList"
}
},
"PM_x0020_NameId": 220,
"St_x0020_Name": "<div class=\"ExternalClassA14DB0FF86994403B827D91158CF34B0\">KO</div>",
}]
}}
I created these model classes:
public class SharepointDTO
{
public class Metadata
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("uri")]
public string uri { get; set; }
[JsonProperty("etag")]
public string etag { get; set; }
[JsonProperty("type")]
public string type { get; set; }
}
public class Deferred
{
[JsonProperty("uri")]
public string uri { get; set; }
}
public class Folder
{
[JsonProperty("__deferred")]
public Deferred __deferred { get; set; }
}
public class ParentList
{
[JsonProperty("__deferred")]
public Deferred __deferred { get; set; }
}
public class Result
{
[JsonProperty("__metadata")]
public Metadata __metadata { get; set; }
[JsonProperty("Folder")]
public Folder Folder { get; set; }
[JsonProperty("ParentList")]
public ParentList ParentList { get; set; }
[JsonProperty("PM_x0020_NameId")]
public int PM_x0020_NameId { get; set; }
[JsonProperty("St_x0020_Name")]
public string St_x0020_Name { get; set; }
}
public class D
{
[JsonProperty("results")]
public IList<Result> results { get; set; }
}
public class RootObject
{
[JsonProperty("d")]
public D d { get; set; }
}
}
No trying to call the rest service from the Web API and need to get the St_x0020_Name from response and store in a string.
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
string StName = retSharepointobj.d.results.St_x0020_Name.ToString();
I am deserializing the JSON in the GetfromSharepoint method like
using (var client_sharePoint = new HttpClient(handler))
{
var response = client_sharePoint.GetAsync(SP_URL).Result;
var responsedata = await response.Content.ReadAsStringAsync();
var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(responsedata);
return returnObj;
}
But it throws an error:
'System.Collections.Generic.IList' does not contain a definition for 'St_x0020_Name' and no extension method 'St_x0020_Name' accepting a first argument of type 'System.Collections.Generic.IList' could be found (are you missing a using directive or an assembly reference?)
results is an array, so you have either loop thru like
foreach(var item in retSharepointobj.d.results){
string StName = item.St_x0020_Name.ToString();
}
or get a specific element, for example a first element like:
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
string StName = retSharepointobj.d.results[0].St_x0020_Name.ToString();
or you can add an extra check like that
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
if(retSharepointobj.d.results.length > 0){
string StName = retSharepointobj.d.results[0].St_x0020_Name.ToString();
}
Shouldn't this line:
string StName = retSharepointobj.d.results.St_x0020_Name.ToString();
Be like this?
string StName = retSharepointobj.d.results.First().St_x0020_Name.ToString();