Convert HTTPResponse Message (Json) - c#

I am trying to convert the content of a response message to a list of items contained within the response message and keep running into issues, the returned json looks like this:
Jason output
Here is the whole returned response content:
{
"Version": 1,
"Result": "Success",
"Data": {
"Tasks": [
{
"Oid": "f70b1a46-690f-4637-886b-f90f035a11e8",
"CreatedOn": "2022-07-15T00:07:41.553Z",
"ChangedOn": "2022-07-15T03:39:58.373Z",
"Subject": "233817 3693 Range Rd",
"Description": "",
"Comment": "",
"IsStarted": true,
"IsFinished": true,
"IsFinalAppointment": false,
"ScheduledOn": "2022-07-15T09:37:41.553",
"ProductionDeadline": "0001-01-01T00:00:00",
"ScheduledStart": "2022-07-15T09:45:00",
"ScheduledEnd": "2022-07-15T09:50:00",
"RealStart": "2022-07-15T09:45:00",
"RealEnd": "2022-07-15T09:50:00",
"CalculatedSeconds": 300.0000,
"IdleSeconds": 0,
"ScheduledDuration": "PT5M",
"RealDuration": "PT5M",
"Status": 2,
"PercentComplete": 100,
"HasFinishedItems": true,
"IsCustomTask": false,
"AppointmentType": "OrderSpecificAppointment",
"OrderItemCount": 31,
"OrderItemPartsCount": 56,
"MaterialUsageTotal": 58.3280000000,
"MaterialUsageTotalConverted": 58.328,
"MaterialUsageNet": 46.9659000000,
"MaterialUsageNetConverted": 46.9659,
"MaterialUsageScrap": 11.3621000000,
"MaterialUsageScrapConverted": 11.3621,
"MaterialUsageTotalWeight": 263.4676,
"MaterialUsageTotalWeightConverted": 263.4676,
"MaterialUsageNetWeight": 212.1449000000,
"MaterialUsageNetWeightConverted": 212.14490,
"MaterialUsageScrapWeight": 51.3227000000,
"MaterialUsageScrapWeightConverted": 51.32270,
"Station": {
"_Value": "Centurio",
"oid": "f7f3c5fe-49f0-4a9a-b366-29c4ab990fc7"
},
"Materials": [
{
"_Value": "STEALTH MATTE .55 (MONUMENT†)",
"oid": "4889a4f2-75c6-4fb2-b57d-d393ff495ef1",
"externalID": "161539"
}
],
"MaterialCoils": [],
"MaterialDimensions": [],
"PreviousDependencies": [],
"NextDependencies": [
{
"_Value": "",
"oid": "4699df81-4d5c-456c-904d-389a08f60a82",
"start": "2022-07-17T03:37:00",
"station": "Unallocated Folding Station"
}
]
},
{
"Oid": "4699df81-4d5c-456c-904d-389a08f60a82",
"CreatedOn": "2022-07-15T00:07:41.567Z",
"ChangedOn": "2022-07-15T08:27:19.297Z",
"Subject": "233817 3693 Range Rd",
"Description": "",
"Comment": "",
"IsStarted": true,
"IsFinished": true,
"IsFinalAppointment": true,
"ScheduledOn": "2022-07-15T09:37:41.567",
"ProductionDeadline": "0001-01-01T00:00:00",
"ScheduledStart": "2022-07-17T03:37:00",
"ScheduledEnd": "2022-07-17T06:33:00",
"RealStart": "2022-07-17T03:37:00",
"RealEnd": "2022-07-17T06:33:00",
"CalculatedSeconds": 10560.0000,
"IdleSeconds": 0,
"ScheduledDuration": "PT2H56M",
"RealDuration": "PT2H56M",
"Status": 2,
"PercentComplete": 100,
"HasFinishedItems": true,
"IsCustomTask": false,
"AppointmentType": "OrderSpecificAppointment",
"OrderItemCount": 31,
"OrderItemPartsCount": 56,
"MaterialUsageTotal": 46.9659000000,
"MaterialUsageTotalConverted": 46.9659,
"MaterialUsageNet": 46.9659000000,
"MaterialUsageNetConverted": 46.9659,
"MaterialUsageScrap": 0.0000000000,
"MaterialUsageScrapConverted": 0.0,
"MaterialUsageTotalWeight": 212.1449,
"MaterialUsageTotalWeightConverted": 212.1449,
"MaterialUsageNetWeight": 212.1449000000,
"MaterialUsageNetWeightConverted": 212.14490,
"MaterialUsageScrapWeight": 0.0000000000,
"MaterialUsageScrapWeightConverted": 0.00000,
"Station": {
"_Value": "Unallocated Folding Station",
"oid": "7ce5334a-b05c-4511-be7b-1a83d2bf8d4c"
},
"Materials": [
{
"_Value": "STEALTH MATTE .55 (MONUMENT†)",
"oid": "4889a4f2-75c6-4fb2-b57d-d393ff495ef1",
"externalID": "161539"
}
],
"PreviousDependencies": [
{
"_Value": "",
"oid": "f70b1a46-690f-4637-886b-f90f035a11e8",
"start": "2022-07-15T09:45:00",
"station": "Centurio"
}
],
"NextDependencies": []
}
]
},
"Details": ""
}
I wish to extract each task from the "Tasks" element into a list (I have created a class to hold each Task element). So far my code looks like this:
public async void AppointmentsAsync(int taskScheduleID)
{
HttpResponseMessage taskList;
using (RevSchedDataContext context = new RevSchedDataContext())
{
string TimePrint = ConfigurationManager.AppSettings["TimePrint"];
schedule = (from s in context.TaskSchedules.Where(x => x.TaskScheduleID == taskScheduleID) select s).FirstOrDefault();
client.BaseAddress = new Uri("http://bendex.revroof.com.au/microsea/BendexRevBend/import/1.0/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
taskList = await client.GetAsync($"{client.BaseAddress}GetOrderScheduledTasksListJson?did=233817");
var products = await taskList.Content.ReadAsStringAsync();
var mtLists = JsonConvert.DeserializeObject<BendexTaskList>(products);
}
}
When putting a breakpoint on mtLists line and stepping mtLists never get populated.
Regards
Peter

I have found a solution to my problem thanks to the following site: https://json2csharp.com/
This enabled me to create the correct required classes to deserialize the json output in the format required to process.
New calling code:
Root scheduledTaskList = JsonConvert.DeserializeObject<Root>(products);
foreach(var tsk in scheduledTaskList.Data.Tasks)
{
//ToDo: pull required data and update table
}
Regards
Peter

Related

GetDiscoveryDocumentAsync: "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."

I have checked most of the questions on SO, but didn't find my answer.
I'm trying to get a JWT token from a Identity server.
Here's how:
var discoveryDocument = new DiscoveryDocumentRequest
{
Address = "https://admin.blabla.app:5000/",
Policy =
{
RequireHttps = false
}
};
var auth = httpClient.GetDiscoveryDocumentAsync(discoveryDocument).Result;
The error I'm getting is An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.
DiscoveryDocumentRequest
{
"Policy": {
"LoopbackAddresses": [
"localhost",
"127.0.0.1"
],
"Authority": "https://admin.blabla.app:5000",
"AuthorityValidationStrategy": {},
"RequireHttps": false,
"AllowHttpOnLoopback": true,
"ValidateIssuerName": true,
"ValidateEndpoints": true,
"EndpointValidationExcludeList": [],
"AdditionalEndpointBaseAddresses": [],
"RequireKeySet": true
},
"Address": "https://admin.blabla.app:5000/",
"ClientId": null,
"ClientSecret": null,
"ClientAssertion": {
"Type": null,
"Value": null
},
"ClientCredentialStyle": 1,
"AuthorizationHeaderStyle": 0,
"Parameters": [],
"Version": {
"Major": 1,
"Minor": 1,
"Build": -1,
"Revision": -1,
"MajorRevision": -1,
"MinorRevision": -1
},
"Content": null,
"Method": {
"Method": "GET"
},
"RequestUri": null,
"Headers": [
{
"Key": "Accept",
"Value": [
"application/json"
]
}
],
"Properties": {}
}
This code is on a windows service.
Fun fact: Same code works on different windows machines. Why? What might be the problem?
Refer to this sample and please write:
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://admin.blabla.app:5000/");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
please check your URL https://admin.blabla.app:5000/ your error is related to your URL you can test your code by https://demo.identityserver.io/

Google API Explorer doesn't create Compute Engine VM instance

as in title, I am trying to use Google API Explorer to run vm instance. I am using instances.insert for this, but I can't get it to work. After successfuly executing the call I can not see any newly creted vm instance in https://console.cloud.google.com/compute/instances
The request I am trying to execute is copied from Equivalent REST request in Google Cloud Console Create an instance web page :
{
"name": "some-name",
"machineType": "projects/my-project-id/zones/europe-west3-c/machineTypes/f1-micro",
"displayDevice": {
"enableDisplay": false
},
"metadata": {
"items": [
{
"key": "startup-script",
"value": "#! /bin/bash\necho hello\nEOF"
}
]
},
"tags": {
"items": []
},
"disks": [
{
"type": "PERSISTENT",
"boot": true,
"mode": "READ_WRITE",
"autoDelete": true,
"deviceName": "some-name",
"initializeParams": {
"sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200910",
"diskType": "projects/my-project-id/zones/europe-west3-c/diskTypes/pd-standard",
"diskSizeGb": "10",
"labels": {}
},
"diskEncryptionKey": {}
}
],
"canIpForward": false,
"networkInterfaces": [
{
"subnetwork": "projects/my-project-id/regions/europe-west3/subnetworks/default",
"accessConfigs": [
{
"name": "External NAT",
"type": "ONE_TO_ONE_NAT",
"networkTier": "PREMIUM"
}
],
"aliasIpRanges": []
}
],
"description": "",
"labels": {},
"scheduling": {
"preemptible": false,
"onHostMaintenance": "MIGRATE",
"automaticRestart": true,
"nodeAffinities": []
},
"deletionProtection": false,
"reservationAffinity": {
"consumeReservationType": "ANY_RESERVATION"
},
"serviceAccounts": [
{
"email": "some-number-compute#developer.gserviceaccount.com",
"scopes": [
"https://www.googleapis.com/auth/cloud-platform"
]
}
],
"shieldedInstanceConfig": {
"enableSecureBoot": false,
"enableVtpm": true,
"enableIntegrityMonitoring": true
},
"confidentialInstanceConfig": {
"enableConfidentialCompute": false
}
}
Here is the response with status 200
{
"id": "2981010757915612255",
"name": "operation-1602235056020-5b1396b5c5cee-e0e30499-4d06ce75",
"zone": "https://www.googleapis.com/compute/v1/projects/my-project-id/zones/europe-west3-c",
"operationType": "insert",
"targetLink": "https://www.googleapis.com/compute/v1/projects/my-project-id/zones/europe-west3-c/instances/ams2-linux-race-1",
"targetId": "1541614827291382879",
"status": "RUNNING",
"user": "email#gmail.com",
"progress": 0,
"insertTime": "2020-10-09T02:17:36.818-07:00",
"startTime": "2020-10-09T02:17:36.821-07:00",
"selfLink": "https://www.googleapis.com/compute/v1/projects/my-project-id/zones/europe-west3-c/operations/operation-1602235056020-5b1396b5c5cee-e0e30499-4d06ce75",
"kind": "compute#operation"
}
I have the same issue with C# code example from https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert#examples
I can execute the same request without errors and in response I am getting this
{
"clientOperationId":null,
"creationTimestamp":null,
"description":null,
"endTime":null,
"error":null,
"httpErrorMessage":null,
"httpErrorStatusCode":null,
"id":3283200477858999168,
"insertTime":"2020-10-09T00:46:55.187-07:00",
"kind":"compute#operation",
"name":"operation-1602229614262-5b1382701b989-381126a6-cc145485",
"operationType":"insert",
"progress":0,
"region":null,
"selfLink":"https://www.googleapis.com/compute/v1/projects/my-project-id/zones/europe-west3-c/operations/operation-1602229614262-5b1382701b989-381126a6-cc145485",
"startTime":"2020-10-09T00:46:55.189-07:00",
"status":"RUNNING",
"statusMessage":null,
"targetId":2365846324436118401,
"targetLink":"https://www.googleapis.com/compute/v1/projects/my-project-id/zones/europe-west3-c/instances/some-name",
"user":"email#gmail.com",
"warnings":null,
"zone":"https://www.googleapis.com/compute/v1/projects/my-project-id/zones/europe-west3-c",
"ETag":null
}
but I can't see any new instance beeing created...
Does any one know what is the issue here?
The Compute Engine API is enabled. Result of gcloud services list:
NAME TITLE
...
compute.googleapis.com Compute Engine API
...
Can you please double check if Compute Engine Api is enabled and post the result in your question.
gcloud services list
I believe your Compute Engine Api is not enabled.

C# Get Json sub values

I have a API response has a structure like shown below. How can I get the values from this Json string?
[
{
"id": xxx,
"profileId": xxx,
"recipientId": xxx,
"creationTime": "xxxx",
"modificationTime": "xxxx",
"active": true,
"eligible": true,
"balances": [
{
"balanceType": "AVAILABLE",
"currency": "EUR",
"amount": {
"value": 55555,
"currency": "EUR"
},
"reservedAmount": {
"value": 0,
"currency": "EUR"
},
"bankDetails": {
"id": xxx,
"currency": "EUR",
"bankCode": "code",
"accountNumber": "account number",
"swift": "swift",
"iban": "iban",
"bankName": "bankName",
"accountHolderName": "accountHolderName",
"bankAddress": {
"addressFirstLine": "bankAddress",
"postCode": "xxxxx",
"city": "xxxxx",
"country": "xxxxx",
"stateCode": null
}
}
}
]
}
]
I am using The below extension method to get data for some other API's I have integrated in my system. This works fine for the other API's I have integrated.
public static string GetJsonField(RestSharp.IRestResponse value, string res)
{
Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(value.Content);
res = json.GetValue(res).ToString();
return res;
}
Thanks in advance
Copy that Json in json2csharp.com, it will give you the classes that you will need to convert the Json in a c# object.
Then just use var myJson = JsonConverter.deserialize(Json) ;
And you can access to the Json properties as you do with any other class

Outlook API 555 Routing Failure when creating email draft

Our application has a feature that allows users to send emails directly from within the application using the Outlook Rest Api. We create a draft, optionally add attachments to it, and then send the email. This is done in C# using RestSharp.
Some of our users have run into issues when creating the draft. I have been unable to decipher what the error message really means, and if the correct answer is to just retry. (Some users manually try again and it appears to fail multiple times in quick succession). Those same users will then see successful emails sent later.
For reference, the api endpoint is: https://outlook.office.com/api/v2.0/me/messages and the reference documentation is here: https://msdn.microsoft.com/en-us/office/office365/api/mail-rest-operations#CreateNewDraft
Sample Rest Response:
{
"Request": {
"AlwaysMultipartFormData": false,
"JsonSerializer": {
"ContentType": "application/json"
},
"XmlSerializer": {
"ContentType": "text/xml"
},
"UseDefaultCredentials": false,
"Parameters": [
{
"Name": "Authorization",
"Value": "Bearer [[REMOVED]]",
"Type": 3
},
{
"Name": "Content-Type",
"Value": "application/json; charset=utf-8",
"Type": 3
},
{
"Name": "application/json",
"Value": "[[MIME MESSAGE]]",
"Type": 4
},
{
"Name": "Accept",
"Value": "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml",
"Type": 3
}
],
"Files": [],
"Method": 1,
"Resource": "api/v2.0/me/messages",
"RequestFormat": 1,
"OnBeforeDeserialization": {
"Delegate": {},
"method0": {
"Name": "<.ctor>b__0",
"AssemblyName": "RestSharp, Version=105.2.3.0, Culture=neutral, PublicKeyToken=null",
"ClassName": "RestSharp.RestRequest",
"Signature": "Void <.ctor>b__0(RestSharp.IRestResponse)",
"Signature2": "System.Void <.ctor>b__0(RestSharp.IRestResponse)",
"MemberType": 8,
"GenericArguments": null
}
},
"Timeout": 0,
"ReadWriteTimeout": 0,
"Attempts": 1
},
"ContentType": "",
"ContentLength": 0,
"ContentEncoding": "",
"Content": "",
"StatusCode": 555,
"StatusDescription": "Routing Failure",
"RawBytes": "",
"ResponseUri": "https://outlook.office.com/api/v2.0/me/messages",
"Server": "",
"Cookies": [
{
"Comment": "",
"Discard": false,
"Domain": "outlook.office.com",
"Expired": false,
"Expires": "2019-01-18T04:09:17+00:00",
"HttpOnly": true,
"Name": "exchangecookie",
"Path": "/",
"Port": "",
"Secure": false,
"TimeStamp": "2018-01-18T04:09:17.2631733+00:00",
"Value": "3b0a8015b9e24496bf28f9c6010e022a",
"Version": 0
},
{
"Comment": "",
"Discard": false,
"Domain": "outlook.office.com",
"Expired": false,
"Expires": "2018-01-18T04:24:17+00:00",
"HttpOnly": false,
"Name": "X-RouteRefreshCookie",
"Path": "/",
"Port": "",
"Secure": false,
"TimeStamp": "2018-01-18T04:09:17.2631733+00:00",
"Value": "zoHNz87H0s/O0s7Hq8/Lxc/Gxc7IgbKot6+tz8u8vs/Py8mBqoGwlpvFzZrOnsybzJvSzsqcx9LLy8zO0seempzSzsqdy53MyJyZz83N2svPycfIyMmanM3Syp6dndLLzMfJ0p6cy83SycqdnMjNy52Zms+dwruei56dnoyauIqWm8XPm5nPzM/KmdKbz8eb0svPz8fSncbOz9LPmsybzZzNzcbPx5vay8/Jx8jIyZqczdLKnp2d0svMx8nSnpzLzdLJyp2cyM3LnZmaz53ay8+RnpKPjZvNz9GPjZCb0ZCKi5OQkJTRnJCS2svPz7/OzM7Jz8jNzc7KyMzHzMzLyMc=",
"Version": 0
}
],
"Headers": [
{
"Name": "Set-Cookie",
"Value": "exchangecookie=3b0a8015b9e24496bf28f9c6010e022a; expires=Fri, 18-Jan-2019 04:09:17 GMT; path=/; HttpOnly,X-RouteRefreshCookie=zoHNz87H0s/O0s7Hq8/Lxc/Gxc7Igayxzq+tzsi8vs/PzsyBqoGwlpvFzZrOnsybzJvSzsqcx9LLy8zO0seempzSzsqdy53MyJyZz83N2svPycfIyMmanM3Syp6dndLLzMfJ0p6cy83SycqdnMjNy52Zms+dwruei56dnoyauIqWm8XPm5nPzM/KmdKbz8eb0svPz8fSncbOz9LPmsybzZzNzcbPx5vay8/Jx8jIyZqczdLKnp2d0svMx8nSnpzLzdLJyp2cyM3LnZmaz53ay8+RnpKPjZvNz9GPjZCb0ZCKi5OQkJTRnJCS2svPz7/OzM7Jz8jNzc7KyMzHzMzLyMc=; expires=Thu, 18-Jan-2018 04:24:17 GMT; path=/,X-RouteRefreshCookie=zoHNz87H0s/O0s7Hq8/Lxc/Gxc7IgbKot6+tz8u8vs/Py8mBqoGwlpvFzZrOnsybzJvSzsqcx9LLy8zO0seempzSzsqdy53MyJyZz83N2svPycfIyMmanM3Syp6dndLLzMfJ0p6cy83SycqdnMjNy52Zms+dwruei56dnoyauIqWm8XPm5nPzM/KmdKbz8eb0svPz8fSncbOz9LPmsybzZzNzcbPx5vay8/Jx8jIyZqczdLKnp2d0svMx8nSnpzLzdLJyp2cyM3LnZmaz53ay8+RnpKPjZvNz9GPjZCb0ZCKi5OQkJTRnJCS2svPz7/OzM7Jz8jNzc7KyMzHzMzLyMc=; expires=Thu, 18-Jan-2018 04:24:17 GMT; path=/",
"Type": 3
},
{
"Name": "request-id",
"Value": "ab8da322-62ac-4c32-b92b-accd590d7aaf",
"Type": 3
},
{
"Name": "X-CalculatedFETarget",
"Value": "SN1PR17CU001.internal.outlook.com",
"Type": 3
},
{
"Name": "X-BackEndHttpStatus",
"Value": "555,555",
"Type": 3
},
{
"Name": "X-FEProxyInfo",
"Value": "SN1PR17CA0013.NAMPRD17.PROD.OUTLOOK.COM",
"Type": 3
},
{
"Name": "X-CalculatedBETarget",
"Value": "SN1PR20MB0286.namprd20.prod.outlook.com",
"Type": 3
},
{
"Name": "x-ms-appId",
"Value": "8410d572-e055-48e5-b2c7-869538daf671",
"Type": 3
},
{
"Name": "X-BEServerRoutingError",
"Value": "Mailbox database change detected; moved from database 0fd6794b-0d64-4c64-be98-dc8157675f93 to 0df0305f-d08d-4008-b910-0e3d2c22908d",
"Type": 3
},
{
"Name": "X-DiagInfo",
"Value": "SN1PR20MB0286",
"Type": 3
},
{
"Name": "X-BEServer",
"Value": "SN1PR20MB0286",
"Type": 3
},
{
"Name": "X-FEServer",
"Value": "SN1PR17CA0013,MWHPR04CA0046",
"Type": 3
},
{
"Name": "X-Powered-By",
"Value": "ASP.NET",
"Type": 3
},
{
"Name": "X-MSEdge-Ref",
"Value": "Ref A: A07C0D2FC267430AA8A2AEEEA095E277 Ref B: BAYEDGE0211 Ref C: 2018-01-18T04:09:17Z",
"Type": 3
},
{
"Name": "Date",
"Value": "Thu, 18 Jan 2018 04:09:16 GMT",
"Type": 3
},
{
"Name": "Content-Length",
"Value": "0",
"Type": 3
}
],
"ResponseStatus": 1
}
Note: I've removed some details like the message itself and the bearer token. If it's necessary for debugging, I can obfuscate and include the information again.
UPDATE: It appears that the error code has changed to 503 Service Unavailable instead of 555 Routing Failure, but the details seem to be the same. The key response header is "X-BEServerRoutingError" that contains a value like "Mailbox database change detected; moved from database [guid] to [guid]". Based on the response from this SO question: Office365 API Error "Mailbox database change detected;", it appears that this is a known transient issue and the resolution is to just retry. There doesn't seem to be any guidance on amount of times to retry or anything like that. Still on the lookout for an answer that has proper guidance.
After a long support ticket conversation with Microsoft, their guidance was to add a retry policy.
My example above doesn't show it, but there is usually a header with the name of "X-Retry-After" that has an integer value that represents minutes. If the value is 0, it means to retry immediately.
After implementing the retry policy, we haven't seen anymore errors for roughly a week and a half.

how to build a good c# data structure

my aim is to develop a custom search based on goeuro.com(overview) in my spare time.
I simplyfied the search parameters to the minimum.
For example(you can try this, as loong as the search_id is valid):
http://www.goeuro.com/GoEuroAPI/rest/api/v5/results?&search_id=428558909
The search_id will be generated when you visit http://www.goeuro.com and enter the first time your search parameters.
This is the simplified data structure I generated from http://json2csharp.com/ using this as my input JSON:
{
"serviceVersion": "v1.0.0",
"sortVariants": null,
"companies": {
"1007": {
"name": "Eurolines Germany",
"logoUrl": "http://cdn-goeuro.com/static_content/web/logos/{size}/eurolines_germany.png",
"id": "1007"
}
},
"outbounds": {
"3624107261930718525-38-flight-1-27": {
"companyId": "38",
"mode": "flight",
"duration": "873",
"outboundId": "3624107261930718525",
"journeyId": "27",
"departureTime": "2017-01-15T19:12:00.000+01:00",
"arrivalTime": "2017-01-16T09:45:00.000+01:00",
"stops": "1",
"price": 16209,
"updatedAt": "1",
"segments": [ 1344486303, 574447503, 689435565, 833161604 ],
"arrivalOvernightOffset": 1,
"overnightOffset": 1
}
},
"query": {
"roundTrip": false,
"airportToAirport": false,
"locationsOutsideEurope": false,
"searchId": "428558909",
"departurePosition": "377001",
"arrivalPosition": "398532",
"departureDate": "2017-01-15T00:00:00.000+01:00",
"passengers": {
"adults": 1,
"children": 0,
"infants": 0
},
"userInfo": {
"userLocale": "en",
"userCurrency": "EUR"
},
"searchModes": {
"bus": {
"status": "done",
"resultsQty": 13,
"filteredResultsQty": 13
},
"flight": {
"status": "done",
"resultsQty": 276,
"filteredResultsQty": 276
},
"train": {
"status": "done",
"resultsQty": 4,
"filteredResultsQty": 4
}
}
},
"itineraries": [
{ "outboundLegId": "3624107261930718525-38-flight-1-27" }
],
"segmentDetails": {
"1002857016": {
"type": "flight",
"departureTime": "2017-01-16T08:35:00.000+01:00",
"arrivalTime": "2017-01-16T12:05:00.000+02:00",
"departurePosition": "313870",
"arrivalPosition": "314920",
"duration": "150",
"company": "190",
"transportId": "ca6199",
"direction": "OUTBOUND",
"overnightOffset": 1,
"departureOvernightOffset": 1,
"arrivalOvernightOffset": 1
}
},
"positions": {
"2091737": {
"positionType": "busstation",
"name": "Warszawa, Warszawa Centralny",
"cityName": "Warsaw",
"latitude": 52.22782,
"longitude": 21.00224
}
},
"currencies": {
"EUR": {
"name": "Euro",
"symbol": "€"
}
}
}
The result from http://json2csharp.com/ is pretty good, but on the other side it generates something like this
public class Outbounds
{
public __invalid_type__362410726193071852538Flight127 __invalid_name__3624107261930718525-38-flight-1-27 { get; set; }
}
I see two problems here:
using __invalid_name__3624107261930718525-38-flight-1-27 is not a valid identifier in c#
and the above mentioned name is some random name, which I can not rely on my data structure.
So, my actually questions are:
How can I handle the request ?
How shall the data structure look like ?
By the way this is the code I am using(plus the generated results from http://json2csharp.com/):
static void Main()
{
var client = new RestClient("https://www.goeuro.com");
var request = new RestRequest("/GoEuroAPI/rest/api/v5/results?&search_id=428558909", Method.GET);
request.RequestFormat = DataFormat.Json;
// contentType: "application/json; charset=utf-8",
var response = client.Execute<Response>(request).Data;
}
Actually I found an existing solution(partly) for my problem:
https://github.com/evgenTraytyak/goeuro-api
, which is actually written in node.js, but I need c#, but by the way this example does not quite work(only if you have an existing search_id) and at the end I want to get the search_id from goeuro, without manually type it to my code.
Maybe the reason that using this is that the JSON-Format changed...

Categories

Resources