VB.NETでJSONをデシリアライズ
2018/03/28
VB.NETでJSONをデシリアライズする方法のメモ。
1.Serialization アセンブリへの参照を追加
「System.Runtime.Serialization」への参照を追加する
2.JSONに対応するクラスをつくる
Public Class sample_json
Public Property code As String
Public Property name As String
Public Property stat As Integer
Public Property flag As Boolean
End Class
3.デシリアライズする関数作成
Imports System.IO
Imports System.Runtime.Serialization.Json
Imports System.Text
Private Function Deserialize(Of UserClass)(json As String) As UserClass
Dim serializer As New DataContractJsonSerializer(GetType(UserClass))
Dim stream As New MemoryStream(Encoding.UTF8.GetBytes(json))
Try
Return DirectCast(serializer.ReadObject(stream), UserClass)
Catch ex As Exception
Throw
Finally
stream.Dispose()
stream = Nothing
serializer = Nothing
End Try
End Function
ちなみにシリアライズは、こんの感じか。
Private Function Serialize(target As Object) As String
Dim serializer As New DataContractJsonSerializer(target.GetType)
Dim stream As New MemoryStream
Try
serializer.WriteObject(stream, target)
Return Encoding.UTF8.GetString(stream.ToArray())
Catch ex As Exception
Throw
Finally
stream.Dispose()
stream = Nothing
serializer = Nothing
End Try
End Function
4.呼び出し
Dim json As String = "{""code"":""001"",""name"":""abc"",""stat"":2,""flag"":false}"
Dim sj As sample_json = Deserialize(Of sample_json)(json)
補足
Json.NETというライブラリがあり、場合によっては、それを利用する手もある。