VB.net JSON 反序列化 [英] VB.net JSON Deserialize

查看:59
本文介绍了VB.net JSON 反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got the following JSON string to deserialize:

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

我正在使用 DataContractJsonSerializer 方法.

I'm using DataContractJsonSerializer method.

它由项目数组组成,我找不到可以反序列化此结构的使用 VB.Net 的示例.我有以下应用程序类来存储此信息:

It is made up of array of items and I couldn't find an example using VB.Net that can deserialize this structure. I have the following Application class to store this information:

    <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

推荐答案

我建议您使用 JavaScriptSerializer 而不是 DataContractJsonSerializer.原因如下:

I'd recommend you to use JavaScriptSerializer over DataContractJsonSerializer. The reasons are:

  • JavaScriptSerializerDataContractJsonSerializer
  • 更快
  • DataContractJsonSerializer 需要比 JavaScriptSerializer 更多的代码来实现简单的序列化.
  • JavaScriptSerializer is faster over DataContractJsonSerializer
  • DataContractJsonSerializer requires more code than JavaScriptSerializer for a simple serialization.

您不需要 DataContractDataMember 属性与 JavaScriptSerializer

You won't need the DataContract and DataMember attribute to use along with 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:

And use this to deserialize your jsonText:

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

如果你还想使用DataContractJsonSerializer,你可以使用下面这段代码反序列化:

If you still want to use DataContractJsonSerializer, you can use this code below to deserialize:

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 代码转换器

这篇关于VB.net JSON 反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆