Parsing JSON in VB.NET

Mattepuffo's logo
Parsing JSON in VB.NET

Parsing JSON in VB.NET

Anche per il Visual Baisc.NET ho deciso di usare la libreria Json.NET per effettuare il parsing dei dati in formato JSON.

La potete installare tramite NuGet.

La documentazione prevede gli esempi in C#, ma tramite i consigli del forum HTML.it, sono riuscito ad adattarla al VB.NET.

Cominciamo da una classe POJO:

Public Class Book
    Public title As String
    Public author As String
End Class

Questo il codice per la richiesta al servizio remoto usando HttpClient:

Imports System.Net.Http
Imports Newtonsoft.Json

Module Module1

    Sub Main()
        Dim t As Task = New Task(AddressOf SendRequest)
        t.Start()
        Console.WriteLine("Inizio richiesta")
        Console.ReadLine()
    End Sub

    Async Sub SendRequest()
        Dim uri As New Uri("https://www.sito.com/file.php")
        Dim books As List(Of Book) = New List(Of Book)
        Using client As HttpClient = New HttpClient
            Using response As HttpResponseMessage = Await client.GetAsync(uri)
                Using content As HttpContent = response.Content
                    Dim result As String = Await content.ReadAsStringAsync()
                    If result IsNot Nothing Then
                        Dim json As String = result.ToString()
                        Dim list As List(Of Book) =
                            JsonConvert.DeserializeObject(Of List(Of Book))(json)
                        For Each item As Book In list
                            books.Add(item)
                        Next
                    End If
                End Using
            End Using
        End Using

        For Each book As Book In books
            Console.WriteLine(book.title + " - " + book.author)
        Next
    End Sub

End Module

Enjoy!


Condividi

Commentami!