微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VB.net解析Json数据(附类库+Demo)

今天整理电脑的时候,偶然看到一年前使用Vb.net开发的点餐项目,翻腾翻腾找到了这个东西。
记得当时使用Vb.net做了一个服务器,需要对Json数据进行解析。在Android或者C#上有比较成熟的Json解析工具类,在Vb.net上还没有。在国外一家网站上找到的这个类库。现在整理出来,供有需要的人使用。
这个类库仅支持ObjectToString,StringToObject简单的转换,在此基础上我进行了扩展,让其支持Object[]到JsonString的相互转换。这两个方法文章最后给出(注:这两个方法没有编译到类库中,可以自己根据源码编译进去)。

需要注意一点:如果类的属性包含日期类型Date,该类库会抛出NotImplementedException错误,因为Json标准里没有定义Date类型。
日期格式转为字符串处理即可(我是这么处理的)。
先来介绍一下这个类库的使用方法
ObjectToString 方法实例:
Imports PW.JSON

Module Module1

  Class Prova

    Private _id As Integer
    Private _name As String
    Private _valido As Boolean
    Private _subObject As Prova
    Private _numero As Integer
    Private _numeroDec As Double
    Private _array() As String

    Public Property ID() As Integer
      Get
        Return _id
      End Get
      Set(ByVal value As Integer)
        _id = value
      End Set
    End Property

    Public Property Name() As String
      Get
        Return _name
      End Get
      Set(ByVal value As String)
        _name = value
      End Set
    End Property

    Public Property Valido() As Boolean
      Get
        Return _valido
      End Get
      Set(ByVal value As Boolean)
        _valido = value
      End Set
    End Property

    Public Property SubObject() As Prova
      Get
        Return _subObject
      End Get
      Set(ByVal value As Prova)
        _subObject = value
      End Set
    End Property

    Public Property NumeroDec() As Double
      Get
        Return _numeroDec
      End Get
      Set(ByVal value As Double)
        _numeroDec = value
      End Set
    End Property

    Public Property Array() As String()
      Get
        Return _array
      End Get
      Set(ByVal value As String())
        _array = value
      End Set
    End Property

    Public Sub New(ByVal ID As Integer,ByVal Name As String)
      _id = ID
      _name = Name
    End Sub

    Public Function SomeMethod() As String
      Return "Method: " & _id
    End Function

  End Class

Sub Main()
    Dim objprova As New Prova(1,"Nome Object")
    objprova.Array = Split("A E I O U")
    objprova.NumeroDec = 100.34
    objprova.SubObject = New Prova(2,"Nome - SubObject")
    objprova.Valido = True
    Console.WriteLine(PW.JSON.JSONHelper.ObjectToString(objprova))
    Console.ReadLine()
 
End Sub
End Module

打印结果为:

{"NumeroDec": 100.34,"Name": "Nome Object","Array": ["A","E","I","O","U"],"SubObject": {"NumeroDec": 0,"Name": "Nome - SubObject","Array": null,"SubObject": null,"Valido": false,"ID": 2},"Valido": true,"ID": 1}

StringToObject方法实例:
Sub Main()

Dim strjson As String = "{""NumeroDec"": 100.34,""Name"": ""Nome Object""," & _
                        " ""Array"": [""A"",""E"",""I"",""O"",""U""]," & _
                        " ""SubObject"": {""NumeroDec"": 0,""Name"": ""Nome - SubObject""," & _
                        " ""Array"": null,""SubObject"": null,""Valido"": false,""ID"": 2}," & _
                        " ""Valido"": true,""ID"": 1}"

Dim objprova As Prova
objprova = PW.JSON.JSONHelper.StringToObject(strjson,GetType(Prova))

Console.WriteLine(objprova.Name)
Console.WriteLine(objprova.SubObject.Name)
Console.ReadLine()
 
End Sub


结果为:
Nome Object
Nome - SubObject

下面是我扩展的ObjectListToString() 方法,思路很简单,循环调用ObjectToString,拼接成[{},{},{}……]形式:
''' <summary>
    ''' 将对象数组拼装成json字符串
    ''' </summary>
    ''' <param name="objectList"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ObjectListToString(ByVal objectList As List(Of Object))
        Dim stringBuilder As New String("")

        stringBuilder += "["
        For Each entity As Object In objectList
            stringBuilder += PW.JSON.JSONHelper.ObjectToString(entity) + ","
        Next
        stringBuilder = stringBuilder.Substring(0,stringBuilder.LastIndexOf(","))
        stringBuilder += "]"
        Return stringBuilder
    End Function



下面是我扩展的StringToObject()方法,思路就是对[{},{}……]进行拆分,去掉首尾的“[”,“]”后,添加逗号“,” ,然后按照“},”进行拆分即可。
    ''' <summary>
    ''' 将Json格式的数据解析成Object
    ''' </summary>
    ''' <param name="jsonData">包含点菜信息的json数据</param>
    ''' <param name="_classtype">转化成sellLogDetail类</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function StringToObjectList(ByVal jsonData As String,ByVal _classtype As Type)

        '传过来的字符串是“[{ },{ },{ }]”,去掉最后面的“]”,加上一个“,”,这样可以按“},”进行拆分
        Dim adatperString = jsonData.Substring(0,jsonData.LastIndexOf("}") + 1) + ","
        '然后按“{”拆分成数组
        Dim str As String() = adatperString.Split("{")
        Dim list As New List(Of SellLogDetail)
        For index = 1 To str.Length - 1
            If (str(index).EndsWith("},")) Then
                '拼装成一个完整的json数据
                Dim strData As String = "{" + str(index).Substring(0,str(index).Length - 1)
                'MsgBox(strData)

                Dim detail As New SellLogDetail
                Try
                    '转化成对象SellLogDetail
                    detail = PW.JSON.JSONHelper.StringToObject(strData,GetType(SellLogDetail))
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try

                list.Add(detail)
            End If
        Next
        '返回列表
        Return list
    End Function



附类库+demo

欢迎访问: 望月听涛

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐