DataContracts如何工作? - 反序列化Json

时间:2010-11-26 22:57:19

标签: asp.net json deserialization datacontractjsonserializer

我从this SO question抓取了一个示例,并构建了我自己的自定义Google Maps对象,用于反序列化json对象。

现在代码就像一个冠军,但我只需要解释它为什么/如何工作。序列化程序是否“尝试”匹配名称,或者正在发生其他事情。

这究竟是做什么的?

以下是正常工作代码。

Imports System.Net
Imports System.Web
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Json
Imports System.Web.Script.Serialization

Namespace Utilities.Apis
    Public NotInheritable Class GoogleGeolocate


        Private Const googleUrl As String = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false"
        Private Sub New()
        End Sub

        Public Shared Function GetLatLon(ByVal address As String) As String
            ''# This is just here to prevent "placeholder" data from being submitted.
            If address = "6789 university drive" Then
                Return Nothing
            End If

            address = HttpUtility.UrlEncode(address)

            Dim url = String.Format(googleUrl, address)

            Dim request = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate")
            request.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate
            Dim serializer As New DataContractJsonSerializer(GetType(GoogleResponse))
            Dim res = DirectCast(serializer.ReadObject(request.GetResponse().GetResponseStream()), GoogleResponse)

            Dim resources As GoogleResponse.Result = res.results(0)
            Dim point = resources.geometry.location.lat
            Dim latlon As New GeolocationLatLon
            With latlon
                .latitude = resources.geometry.location.lat
                .longitude = resources.geometry.location.lng
            End With

            Dim jsonSerializer = New JavaScriptSerializer

            Return jsonSerializer.Serialize(latlon)
        End Function
    End Class

    <DataContract()>
    Public Class GoogleResponse
        <DataMember()>
        Public Property results() As Result()
        <DataContract()>
        Public Class Result
            <DataMember()>
            Public Property geometry As m_Geometry
            <DataContract()>
            Public Class m_Geometry
                <DataMember()>
                Public Property location As m_location
                <DataContract()>
                Public Class m_location
                    <DataMember()>
                    Public Property lat As String
                    <DataMember()>
                    Public Property lng As String
                End Class
            End Class
        End Class

    End Class
End Namespace

这是GeolocationLatLon Poco

Public Class GeolocationLatLon
    Public latitude As String
    Public longitude As String
End Class

当我调用代码时,它非常简单 注意,这是一个MVC控制器,除了显示我正在做的事情

之外,与“问题”无关。
    Function GeoLocation(ByVal address As String) As ContentResult
        Return New ContentResult With {.Content = GoogleGeolocate.GetLatLon(address),
                                       .ContentType = "application/json"}
    End Function

最终结果是

  

{ “纬度”: “50.124300”, “经度”: “ - 114.4979990”}

1 个答案:

答案 0 :(得分:1)

在内部,DataContractJsonSerializer将JSON名称/值对映射到XML信息集。实际上,DataContractJsonSerializer构建在基于XML的DataContractSerializer之上,并处理每个JSON输入和JSON输出,就像处理XML一样。有一个更高级别的抽象层(JSON编写器和JSON阅读器,通过JsonReaderWriterFactory公开)实际上将这个XML转换为JSON和JSON回到内部XML。

请参阅此excellent overview (Mapping Between JSON and XML)以查看DataContractJsonSerializer内部会发生什么,以及它如何解决所有这些问题。