Wie kann ich mich mit einem API-Server verbinden und eine JSON-Query senden?

  • VB.NET

Es gibt 13 Antworten in diesem Thema. Der letzte Beitrag () ist von a.b_om.

    Wie kann ich mich mit einem API-Server verbinden und eine JSON-Query senden?

    Hallo Community,

    Ich schlage mal eine andere Richtung ein. Ich mache jetzt eine Übung mit API. Mein Ziel ist,
    dass man den Abfahrtsort und Ankunftsort eingeben kann, und so alle Zugverbindungen dazu bekommt.

    Das GUI und die Query ist fertig.

    Wie kann ich diese Query jetzt zum API-Server schicken?
    Diese Daten, die ich zurückbekomme, soll auch einer Liste/ein Array gespeichert werden.

    Mein Querybeispiel:
    transport.opendata.ch/v1/conne…?from=Luzern&to=Dallenwil

    Das Array sollte ca. so aussehen:
    Zugart(IR, S4, S1, etc.)AbfahrtsortAnkunftsortAbfahrtszeitAnkunftszeit
    IRLuzernDallenwil12:1012:27
    S4LuzernDallenwil12:2612:58
    IRLuzernDallenwil13:1013:27
    ...............

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „a.b_om“ ()

    VB.NET-Quellcode

    1. Dim wc As New System.Net.WebClient
    2. Dim s As String = wc.DownloadString("http://transport.opendata.ch/v1/connections?from=" & Textbox1.Text & "&to=" & Textbox2.Text)


    Der JSON ist dann in der Variable S.
    Liebe Grüße,
    C.O.D.E

    Testautomatisierung (TA):

    5%
    Du findest meinen Beitrag Hilfreich? :thumbup: Dann drück auf Hilfreich!

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „C.O.D.E“ ()

    @C.O.D.E
    Ich bekomme nachher das:
    {"connections":[],"from":null,"to":null,"stations":{"from":[],"to":[]}}

    Wo sind die Daten und so?
    Wenn ich auf den Link klicke, der ich gepostet habe, bekomme ich fast alle Daten

    Edit:
    Dass das JSON ist, weiss ich, aber wie bekomme ich die Daten in eine Liste/ein Array, der so angeordnet ist, wie im 1. Post erklärt?

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „a.b_om“ ()

    Nein, funktioniert eindeutig.

    Und zum Thema Array: Du musst die Dateien entweder parsen (Substring, Split ect) oder du holst dir einen json-reader!

    -> Vielleicht hilft dir das: stackoverflow.com/questions/38…e-json-and-read-in-vb-net
    Bilder
    • 2019-11-21_124659.png

      165,92 kB, 1.634×885, 108 mal angesehen
    Liebe Grüße,
    C.O.D.E

    Testautomatisierung (TA):

    5%
    Du findest meinen Beitrag Hilfreich? :thumbup: Dann drück auf Hilfreich!

    a.b_om schrieb:

    Ich bekomme nachher das:
    Sieh Dir mal den Connectionstring an, bevor Du ihn losschickst. Ich denke mal, der ist nicht in Ordnung.
    Falls Du diesen Code kopierst, achte auf die C&P-Bremse.
    Jede einzelne Zeile Deines Programms, die Du nicht explizit getestet hast, ist falsch :!:
    Ein guter .NET-Snippetkonverter (der ist verfügbar).
    Programmierfragen über PN / Konversation werden ignoriert!
    @RodFromGermany
    Danke, jetzt habe ich es korrigiert.

    @C.O.D.E
    Aber wie kann ich das splitten, oder wie bekomme ich den Reader?

    Es ist das erste mal, dass ich etwas mit API mache.

    Es zu splitten, denke ich, ist es zu riskant, weil es zu viele Daten dort sind und ich den Aufbau von dort nicht überschaubar finde.

    Dieser Beitrag wurde bereits 3 mal editiert, zuletzt von „a.b_om“ ()

    Dafür ist die Klasse HttpClient in System.Net.Http da.
    Du musst die Funktion .GetStringAsync() aufrufen, und schon hast du nen JSON-String.

    Als erstes öffnest du jedoch mal die Query im Browser und kopierst die Rohdaten hier her:
    json2csharp.com/
    Die Seite erzeugt dir alle nötigen Klassen, die du deinem Projekt hinzufügst.

    Als nächstes installierst du das NuGet JSON.NET (Newtonsoft.Json).
    Nun jagst du das, was du aus .GetStringAsync() bekommst, durch JsonConvert.DeserializeObject<RootObject>() und hast dadurch alles was du brauchst in einem RootObject Objekt.
    Mithilfe eines Browsers kannst du dir dann die Daten die du brauchst raussuchen und darstellen:

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „EaranMaleasi“ ()

    Ich habe herausgefunden, dass jeder Datensatz mit {"station": anfängt, wie kann ich danach den JSON splitten?

    Edit:
    @EaranMaleasi
    Sorry dein Post zu spät gesehen.

    Edit2:
    Sorry für die vielen Edits, kann keine Antworten schreiben, bis eine gewisse Zeit abgelaufen ist.
    @EaranMaleasi
    • NuGet installiert
    • Klassen hinzugefügt
    Was ist mit .GetStringAsync()?
    Wie und wo muss ich das machen?
    Wie gehts weiter? Ich mache das eben zum ersten Mal!

    Mein jetztiger ProjektCode:
    Spoiler anzeigen

    VB.NET-Quellcode

    1. Imports System.IO
    2. Imports System.Net
    3. Imports System.Text
    4. Public Class Form1
    5. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    6. label5.Text = ""
    7. label6.Text = ""
    8. label7.Text = ""
    9. label8.Text = ""
    10. label9.Text = ""
    11. label10.Text = ""
    12. End Sub
    13. Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
    14. Try
    15. Dim wc As New System.Net.WebClient
    16. Dim s As String = wc.DownloadString("http://transport.opendata.ch/v1/connections?from=" & textBox1.Text & "&to=" & textBox2.Text)
    17. Dim sArray As Array = s.Split("station")
    18. TextBox3.Text = s
    19. Catch ex As Exception
    20. End Try
    21. End Sub
    22. End Class
    23. Public Class Coordinate
    24. Public Property type As String
    25. Public Property x As Double
    26. Public Property y As Double
    27. End Class
    28. Public Class Station
    29. Public Property id As String
    30. Public Property name As String
    31. Public Property score As Object
    32. Public Property coordinate As Coordinate
    33. Public Property distance As Object
    34. End Class
    35. Public Class Prognosis
    36. Public Property platform As Object
    37. Public Property arrival As Object
    38. Public Property departure As DateTime?
    39. Public Property capacity1st As Object
    40. Public Property capacity2nd As Object
    41. End Class
    42. Public Class Coordinate2
    43. Public Property type As String
    44. Public Property x As Double
    45. Public Property y As Double
    46. End Class
    47. Public Class Location
    48. Public Property id As String
    49. Public Property name As String
    50. Public Property score As Object
    51. Public Property coordinate As Coordinate2
    52. Public Property distance As Object
    53. End Class
    54. Public Class From
    55. Public Property station As Station
    56. Public Property arrival As Object
    57. Public Property arrivalTimestamp As Object
    58. Public Property departure As DateTime
    59. Public Property departureTimestamp As Integer
    60. Public Property delay As Integer?
    61. Public Property platform As String
    62. Public Property prognosis As Prognosis
    63. Public Property realtimeAvailability As Object
    64. Public Property location As Location
    65. End Class
    66. Public Class Coordinate3
    67. Public Property type As String
    68. Public Property x As Double
    69. Public Property y As Double
    70. End Class
    71. Public Class Station2
    72. Public Property id As String
    73. Public Property name As String
    74. Public Property score As Object
    75. Public Property coordinate As Coordinate3
    76. Public Property distance As Object
    77. End Class
    78. Public Class Prognosis2
    79. Public Property platform As Object
    80. Public Property arrival As Object
    81. Public Property departure As Object
    82. Public Property capacity1st As Object
    83. Public Property capacity2nd As Object
    84. End Class
    85. Public Class Coordinate4
    86. Public Property type As String
    87. Public Property x As Double
    88. Public Property y As Double
    89. End Class
    90. Public Class Location2
    91. Public Property id As String
    92. Public Property name As String
    93. Public Property score As Object
    94. Public Property coordinate As Coordinate4
    95. Public Property distance As Object
    96. End Class
    97. Public Class [To]
    98. Public Property station As Station2
    99. Public Property arrival As DateTime
    100. Public Property arrivalTimestamp As Integer
    101. Public Property departure As Object
    102. Public Property departureTimestamp As Object
    103. Public Property delay As Object
    104. Public Property platform As String
    105. Public Property prognosis As Prognosis2
    106. Public Property realtimeAvailability As Object
    107. Public Property location As Location2
    108. End Class
    109. Public Class Coordinate5
    110. Public Property type As String
    111. Public Property x As Double
    112. Public Property y As Double
    113. End Class
    114. Public Class Station3
    115. Public Property id As String
    116. Public Property name As String
    117. Public Property score As Object
    118. Public Property coordinate As Coordinate5
    119. Public Property distance As Object
    120. End Class
    121. Public Class Prognosis3
    122. Public Property platform As Object
    123. Public Property arrival As DateTime?
    124. Public Property departure As DateTime?
    125. Public Property capacity1st As Object
    126. Public Property capacity2nd As Object
    127. End Class
    128. Public Class Coordinate6
    129. Public Property type As String
    130. Public Property x As Double
    131. Public Property y As Double
    132. End Class
    133. Public Class Location3
    134. Public Property id As String
    135. Public Property name As String
    136. Public Property score As Object
    137. Public Property coordinate As Coordinate6
    138. Public Property distance As Object
    139. End Class
    140. Public Class PassList
    141. Public Property station As Station3
    142. Public Property arrival As DateTime?
    143. Public Property arrivalTimestamp As Integer?
    144. Public Property departure As DateTime?
    145. Public Property departureTimestamp As Integer?
    146. Public Property delay As Integer?
    147. Public Property platform As String
    148. Public Property prognosis As Prognosis3
    149. Public Property realtimeAvailability As Object
    150. Public Property location As Location3
    151. End Class
    152. Public Class Journey
    153. Public Property name As String
    154. Public Property category As String
    155. Public Property subcategory As Object
    156. Public Property categoryCode As Object
    157. Public Property number As String
    158. Public Property [operator] As String
    159. Public Property [to] As String
    160. Public Property passList As List(Of PassList)
    161. Public Property capacity1st As Object
    162. Public Property capacity2nd As Object
    163. End Class
    164. Public Class Coordinate7
    165. Public Property type As String
    166. Public Property x As Double
    167. Public Property y As Double
    168. End Class
    169. Public Class Station4
    170. Public Property id As String
    171. Public Property name As String
    172. Public Property score As Object
    173. Public Property coordinate As Coordinate7
    174. Public Property distance As Object
    175. End Class
    176. Public Class Prognosis4
    177. Public Property platform As Object
    178. Public Property arrival As Object
    179. Public Property departure As DateTime?
    180. Public Property capacity1st As Object
    181. Public Property capacity2nd As Object
    182. End Class
    183. Public Class Coordinate8
    184. Public Property type As String
    185. Public Property x As Double
    186. Public Property y As Double
    187. End Class
    188. Public Class Location4
    189. Public Property id As String
    190. Public Property name As String
    191. Public Property score As Object
    192. Public Property coordinate As Coordinate8
    193. Public Property distance As Object
    194. End Class
    195. Public Class Departure
    196. Public Property station As Station4
    197. Public Property arrival As Object
    198. Public Property arrivalTimestamp As Object
    199. Public Property departure As DateTime
    200. Public Property departureTimestamp As Integer
    201. Public Property delay As Integer?
    202. Public Property platform As String
    203. Public Property prognosis As Prognosis4
    204. Public Property realtimeAvailability As Object
    205. Public Property location As Location4
    206. End Class
    207. Public Class Coordinate9
    208. Public Property type As String
    209. Public Property x As Double
    210. Public Property y As Double
    211. End Class
    212. Public Class Station5
    213. Public Property id As String
    214. Public Property name As String
    215. Public Property score As Object
    216. Public Property coordinate As Coordinate9
    217. Public Property distance As Object
    218. End Class
    219. Public Class Prognosis5
    220. Public Property platform As Object
    221. Public Property arrival As DateTime?
    222. Public Property departure As Object
    223. Public Property capacity1st As Object
    224. Public Property capacity2nd As Object
    225. End Class
    226. Public Class Coordinate10
    227. Public Property type As String
    228. Public Property x As Double
    229. Public Property y As Double
    230. End Class
    231. Public Class Location5
    232. Public Property id As String
    233. Public Property name As String
    234. Public Property score As Object
    235. Public Property coordinate As Coordinate10
    236. Public Property distance As Object
    237. End Class
    238. Public Class Arrival
    239. Public Property station As Station5
    240. Public Property arrival As DateTime
    241. Public Property arrivalTimestamp As Integer
    242. Public Property departure As Object
    243. Public Property departureTimestamp As Object
    244. Public Property delay As Integer?
    245. Public Property platform As String
    246. Public Property prognosis As Prognosis5
    247. Public Property realtimeAvailability As Object
    248. Public Property location As Location5
    249. End Class
    250. Public Class Section
    251. Public Property journey As Journey
    252. Public Property walk As Object
    253. Public Property departure As Departure
    254. Public Property arrival As Arrival
    255. End Class
    256. Public Class Connection
    257. Public Property from As From
    258. Public Property [to] As [To]
    259. Public Property duration As String
    260. Public Property transfers As Integer
    261. Public Property service As Object
    262. Public Property products As List(Of String)
    263. Public Property capacity1st As Object
    264. Public Property capacity2nd As Object
    265. Public Property sections As List(Of Section)
    266. End Class
    267. Public Class Coordinate11
    268. Public Property type As String
    269. Public Property x As Double
    270. Public Property y As Double
    271. End Class
    272. Public Class From2
    273. Public Property id As String
    274. Public Property name As String
    275. Public Property score As Object
    276. Public Property coordinate As Coordinate11
    277. Public Property distance As Object
    278. End Class
    279. Public Class Coordinate12
    280. Public Property type As String
    281. Public Property x As Double
    282. Public Property y As Double
    283. End Class
    284. Public Class To2
    285. Public Property id As String
    286. Public Property name As String
    287. Public Property score As Object
    288. Public Property coordinate As Coordinate12
    289. Public Property distance As Object
    290. End Class
    291. Public Class Coordinate13
    292. Public Property type As String
    293. Public Property x As Double
    294. Public Property y As Double
    295. End Class
    296. Public Class From3
    297. Public Property id As String
    298. Public Property name As String
    299. Public Property score As Object
    300. Public Property coordinate As Coordinate13
    301. Public Property distance As Object
    302. End Class
    303. Public Class Coordinate14
    304. Public Property type As String
    305. Public Property x As Double
    306. Public Property y As Double
    307. End Class
    308. Public Class To3
    309. Public Property id As String
    310. Public Property name As String
    311. Public Property score As Object
    312. Public Property coordinate As Coordinate14
    313. Public Property distance As Object
    314. End Class
    315. Public Class Stations
    316. Public Property from As List(Of From3)
    317. Public Property [to] As List(Of To3)
    318. End Class
    319. Public Class RootObject
    320. Public Property connections As List(Of Connection)
    321. Public Property from As From2
    322. Public Property [to] As To2
    323. Public Property stations As Stations
    324. End Class


    Ich weiss, viel Code. Ist es normal, dass es jetzt eine Station-Klasse, eine Station1-Klasse, eine Station2-Klasse, etc. hat?

    Dieser Beitrag wurde bereits 3 mal editiert, zuletzt von „a.b_om“ ()

    a.b_om schrieb:

    Was ist mit .GetStringAsync()?
    Schon meinen Post aufmerksam lesen. Du benutzt ja auch den WebClient, den @C.O.D.E vorgeschlagen hat, der hat diese Funktion natürlich nicht, kommt aber zum selben Ergebnis, ein string, der Json enthält.

    a.b_om schrieb:

    Ich weiss, viel Code. Ist es normal, dass es jetzt eine Station-Klasse, eine Station1-Klasse, eine Station2-Klasse, etc. hat?
    Bei dem erzeugten Json leider ja. Natürlich könntest du, nachdem du alle Daten die du brauchst gefunden hast, alle Klassen die du nicht brauchst, und die Properties die auf diese Klassen verweisen entfernen.
    @EaranMaleasi
    Und wie?

    Wenn ich einen Punkt mache und es anfange zu schreiben, wird es mir nicht vorgeschlagen.

    Ich weiss, dass ich gerade ein vollkommener Noob bin. Entweder das, oder ich stehe auf dem Schlauch.

    Edit
    @EaranMaleasi
    Ich hab das mit ​.GetStringAsync geschafft, aber wie geht es weiter. Der nächste Schritt funktioniert nicht. Auch die Anzeige ist mir föllig unklar

    Dieser Beitrag wurde bereits 3 mal editiert, zuletzt von „a.b_om“ ()

    Ok, jetzt hat es auch geklappt. Wie bekomme ich jetzt den 1., 2. und den 3. Ankunfts-/Abfahrtszeit in verschiedenen variablen?


    VB.NET-Quellcode

    1. Dim wc As New System.Net.WebClient
    2. Dim s As String = wc.DownloadString("http://transport.opendata.ch/v1/connections?from=" & textBox1.Text & "&to=" & textBox2.Text)
    3. Dim journey = JsonConvert.DeserializeObject(Of RootObject)(s)
    In journey.connections findest du die Verbindungen.

    Hier mal, der Code meiner Konsole

    C#-Quellcode

    1. int pad = 15;
    2. Trainz trainz = JsonConvert.DeserializeObject<Trainz>(json);
    3. //Console.WriteLine($"|{"".PadRight(pad * 5 + 4, '=')}|");
    4. Console.WriteLine($"|{"Zugart".PadRight(pad)}" +
    5. $"|{"Abfahrtsort".PadRight(pad)}" +
    6. $"|{"Ankunftsort".PadRight(pad)}" +
    7. $"|{"Abfahrtszeit".PadRight(pad)}" +
    8. $"|{"Ankunftszeit".PadRight(pad)}|");
    9. foreach (Connection item in trainz.connections)
    10. {
    11. Console.WriteLine($"|{"".PadRight(pad * 5 + 4, '=')}|");
    12. Console.WriteLine($"|{item.products[0].PadRight(pad)}" +
    13. $"|{item.from.station.name.PadRight(pad)}" +
    14. $"|{item.to.station.name.PadRight(pad)}" +
    15. $"|{item.from.departure.ToString("HH:mm").PadRight(pad)}" +
    16. $"|{item.to.arrival.ToString("HH:mm").PadRight(pad)}|");
    17. }
    18. Console.WriteLine($"|{"".PadRight(pad * 5 + 4, '=')}|");
    19. Console.ReadKey(true);

    Zum Verständnis ich habe die Klasse RootObject in Trainz umbenannt, sonst aber nicht berührt.

    Wie du siehst, musst du nur durch die Connections iterieren, und bekommst dann alle Daten.

    Das habe ich gefunden, indem ich die Query einfach mit dem FireFox abgesetzt habe, und der dann, neben der Rohdatenansicht, auch diese Ansicht bietet:
    (Ich gehe einfach mal davon aus, dass Chrome usw. ähnliche Ansichten bieten)
    Da die Klassen die du hinzugefügt hast 1:1 die JSON Elemente abbilden, musst du jetzt einfach nur noch die entsprechenden Properties abrufen und schon hast du deine Daten.

    Dieser Beitrag wurde bereits 2 mal editiert, zuletzt von „EaranMaleasi“ ()