簡體   English   中英

VB.net JSON反序列化

[英]VB.net JSON Deserialize

我有以下JSON字符串要反序列化:

[{"application_id":"1","application_package":"abc"},{"application_id":"2","application_package":"xyz"}]

我正在使用DataContractJsonSerializer方法。

它由項目數組組成,我找不到使用VB.Net可以反序列化此結構的示例。 我具有以下Application類來存儲此信息:

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

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

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

    End Class

這是將JSON反序列化為對象的最簡單方法(使用.NET 4):

JSON示例:

{
    "dogs":[],
    "chickens":[
        {
            "name":"Macey",
            "eggs":7
        }, 
        {
            "name":"Alfred",
            "eggs":2
        }
    ]
}

VB.NET:

Try
    Dim j As Object = New JavaScriptSerializer().Deserialize(Of Object)(JSONString)
    Dim a = j("dogs")                   ' returns empty Object() array
    Dim b = j("chickens")(0)            ' returns Dictionary(Of String, Object)
    Dim c = j("chickens")(0)("name")    ' returns String "Macey"
    Dim d = j("chickens")(1)("eggs")    ' returns Integer 2
Catch ex As Exception
    ' in case the structure of the object is not what we expected.
End Try

我建議您在DataContractJsonSerializer上使用JavaScriptSerializer 原因如下:

  • JavaScriptSerializerDataContractJsonSerializer更快
  • 為了進行簡單的序列化, DataContractJsonSerializerJavaScriptSerializer需要更多的代碼。

您不需要將DataContractDataMember屬性與JavaScriptSerializer一起使用

使用此數據類

<Serializable> _
Public Class ApplicationItem
    Public Property application_id() As String
        Get
            Return m_application_id
        End Get
        Set
            m_application_id = Value
        End Set
    End Property
    Private m_application_id As String
    Public Property application_package() As String
        Get
            Return m_application_package
        End Get
        Set
            m_application_package = Value
        End Set
    End Property
    Private m_application_package As String
End Class

並使用它來反序列化您的jsonText

Dim jss As New JavaScriptSerializer()
Dim dict = jss.Deserialize(Of List(Of ApplicationItem))(jsonText)

如果仍要使用DataContractJsonSerializer ,則可以使用下面的代碼反序列化:

Dim obj As New List(Of ApplicationItem)()
Dim ms As New MemoryStream(Encoding.Unicode.GetBytes(json))
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.[GetType]())
obj = DirectCast(serializer.ReadObject(ms), List(Of ApplicationItem))
ms.Close()
ms.Dispose()

禮貌:二手Telerik代碼轉換器

這對我有用:

// Get the HttpWebRequest reaponse
string Response = loResponseStream.ReadToEnd();

var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(Response);
string carrier = (dict["Response"]["carrier"]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM