VB.NETからJSONを読み込んでみるテスト


vbから手軽にJSON読み込みできねぇかなーて調べてたら
DataContractJsonSerializer使えば楽だよ!って見かけたので試しに書いてみた。
とりあえず今ココなうの位置情報のJSONを読んでみたのが以下のコード。

Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Runtime.Serialization

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Call jsonReadtest()
    End Sub

    Private Sub jsonReadtest()
        Try
            Dim url As String = "http://proxy.imacoconow.com/api/latest"
            Dim wc As New WebClient
            Dim ms As New MemoryStream
            Dim sw As New StreamWriter(ms)
            Dim st As Stream = wc.OpenRead(url)
            Dim sr As New StreamReader(st, Encoding.UTF8)
            Dim s As String = sr.ReadToEnd

            '両端の余分な括弧を除去
            s = s.Remove(s.Length - 1, 1).Remove(0, 1)

            sw.Write(s)
            sw.Flush()
            ms.Position = 0

            Dim jsonRead As New Json.DataContractJsonSerializer(GetType(imacocoData.latest))
            Dim o As imacocoData.latest = jsonRead.ReadObject(ms)

            If o.result = 1 Then
                For i As Integer = 0 To o.points.Count - 1
                    With o.points(i)
                        Debug.Print(.nickname & " : " & .lat & ", " & .lon & " ")
                    End With
                Next i
            End If

            '後処理
            sr.Close()
            st.Close()
            sw.Close()
            st.Close()
        Catch ex As Exception
            Debug.Print(ex.Message)
        End Try
    End Sub
End Class

Namespace imacocoData
    Public Class Points
        Public type As String
        Public altitude As Object
        Public lon As String
        Public valid As Boolean
        Public user As String
        Public lat As String
        Public velocity As Object
        Public nickname As String
        Public dir As Object
        Public ustream_status As String
    End Class

    Public Class latest
        Public points As List(Of Points)
        Public result As Integer
    End Class
End Namespace

すごくシンプルでいいと思う、うん。

JSON用の型定義作るのはC#用なら自動でやってくれるサイトいくつかあるけど

VBだと地味に面倒。

フレームワーク2.0時代に自前でパースして連想配列にしていたときと比べれば断然いいよ。

カテゴリー: VB.net パーマリンク