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

欢迎访问: 望月听涛

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...