VB.net JSON反序列化

我有以下的JSONstring反序列化:

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

我正在使用DataContractJsonSerializer方法。

它是由一系列项目组成的,我无法find一个使用VB.Net的例子,可以反序列化这个结构。 我有以下应用程序类来存储此信息:

  <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 

我build议你通过DataContractJsonSerializer使用JavaScriptSerializer 。 原因是:

  • JavaScriptSerializerDataContractJsonSerializer更快
  • 对于简单的序列化, DataContractJsonSerializer需要比JavaScriptSerializer更多的代码。

您不需要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代码转换器

下面是将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 

这适用于我:

 // 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"]);