开发者

Deserialize complex JSON (VB.NET)

开发者 https://www.devze.com 2023-02-10 04:33 出处:网络
I\'m trying to deserialize json returned by some directions API similar to Google Maps API. My JSON is as follows (I\'m using VB.NET 2008):

I'm trying to deserialize json returned by some directions API similar to Google Maps API. My JSON is as follows (I'm using VB.NET 2008):

jsontext = { "version":0.3, "status":0, "route_summary": { "total_distance":300, "total_time":14, "start_point":"43", "end_point":"42" }, "route_geometry":[[51.025421,18.647631],[51.026131,18.6471],[51.027802,18.645639]], "route_instructions": [["Head northwest on 43",88,0,4,"88 m","NW",334.8],["Continue on 42",212,1,10,"0.2 km","NW",331.1,"C",356.3]] }

So far I came up with the following code:

Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim 开发者_Python百科lstTextAreas As Output_CloudMade() = js.Deserialize(Of Output_CloudMade())(jsontext)

I'm not sure how to define complex class, i.e. Output_CloudMade.

I'm trying something like:

Public Class RouteSummary
    Private mTotalDist As Long
    Private mTotalTime As Long
    Private mStartPoint As String
    Private mEndPoint As String


    Public Property TotalDist() As Long
        Get
            Return mTotalDist
        End Get
        Set(ByVal value As Long)
            mTotalDist = value
        End Set
    End Property

    Public Property TotalTime() As Long
        Get
            Return mTotalTime
        End Get
        Set(ByVal value As Long)
            mTotalTime = value
        End Set
    End Property

    Public Property StartPoint() As String
        Get
            Return mStartPoint
        End Get
        Set(ByVal value As String)
            mStartPoint = value
        End Set
    End Property

    Public Property EndPoint() As String
        Get
            Return mEndPoint
        End Get
        Set(ByVal value As String)
            mEndPoint = value
        End Set
    End Property

End Class

Public Class Output_CloudMade

    Private mVersion As Double
    Private mStatus As Long
    Private mRSummary As RouteSummary
    'Private mRGeometry As RouteGeometry
    'Private mRInstructions As RouteInstructions

    Public Property Version() As Double
        Get
            Return mVersion
        End Get
        Set(ByVal value As Double)
            mVersion = value
        End Set
    End Property

    Public Property Status() As Long
        Get
            Return mStatus
        End Get
        Set(ByVal value As Long)
            mStatus = value
        End Set
    End Property

    Public Property Summary() As RouteSummary
        Get
            Return mRSummary
        End Get
        Set(ByVal value As RouteSummary)
            mRSummary = value
        End Set
    End Property


    'Public Property Geometry() As String
    '    Get

    '    End Get
    '    Set(ByVal value As String)

    '    End Set
    'End Property

    'Public Property Instructions() As String
    '    Get

    '    End Get
    '    Set(ByVal value As String)

    '    End Set
    'End Property

End Class

but it does not work. The problem is with complex properties, like route_summary. It is filled with "nothing". Other properties, like "status" or "version" are filled properly.

Any ideas, how to define class for the above JSON?

Can you share some working code for deserializing JSON in VB.NET?

Thanks,


Below is a sample Converter class that will take an incoming stream of JSON and convert to to an object you specify. I should note the below code is .Net 4.0. The JSON serializer in 4 is much easier to use. Let me know if you can't use 4 and I'll see if I can dig up a 3.5 version. Basically you need to create a class structure to map the JSON to a Class. I created the Route and RouteSummary classes for you. I left route_geometry and route_instructions as objects. You should create class definitions for each but this should get you started.

Imports System.IO
Imports System.Runtime.Serialization.Json
Imports System.Runtime.Serialization

<DataContract(Namespace:="")> _
Public Class Route

    <DataMember(Name:="version")>
    Public Property version As Double

    <DataMember(Name:="status")>
    Public Property status As Double

    <DataMember(Name:="route_summary")>
    Public Property route_summary As route_summary

    <DataMember(Name:="route_geometry")>
    Public Property route_geometry As Object()

    <DataMember(Name:="route_instructions")>
    Public Property route_instructions() As Object

End Class

<DataContract(Name:="route_summary", Namespace:="")> _
Public Class route_summary
    <DataMember(Name:="total_distance")>
    Public Property total_distance As Double

    <DataMember(Name:="total_time")>
    Public Property total_time As Double

    <DataMember(Name:="start_point")>
    Public Property start_point As Double

    <DataMember(Name:="end_point")>
    Public Property end_point As Double
End Class

Public Class Converter(Of t)
    Public Function ReturnJSON(ByRef sreader As StreamReader) As t
        If GetType(t).Equals(GetType(String)) Then
            Dim result As Object = sreader.ReadToEnd.Replace("""", "")
            Return result
        Else
            Dim ds As New DataContractJsonSerializer(GetType(t))
            Dim result As t = DirectCast(ds.ReadObject(sreader.BaseStream), t)
            ds = Nothing
            Return result
        End If
    End Function
End Class

    Sub Main()
        Dim json As String = "{""version"":0.3, ""status"":0, ""route_summary"": { ""total_distance"":300, ""total_time"":14, ""start_point"":""43"", ""end_point"":""42"" }, ""route_geometry"":[[51.025421,18.647631],[51.026131,18.6471],[51.027802,18.645639]], ""route_instructions"": [[""Head northwest on 43"",88,0,4,""88 m"",""NW"",334.8],[""Continue on 42"",212,1,10,""0.2 km"",""NW"",331.1,""C"",356.3]]}"

        Dim encoding As New System.Text.UTF8Encoding
        Dim bytes() As Byte = encoding.GetBytes(json)

        Using os As New MemoryStream
            os.Write(bytes, 0, bytes.Length)
            os.Position = 0

            Using reader As New StreamReader(os)
                Dim converter As New Converter(Of Route)
                Dim output As Route

                output = converter.ReturnJSON(reader)

                'output contains data
            End Using
        End Using
    End Sub

See this page for a detailed description of how to read the JSON data. http://www.json.org/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号