[VB.NET] JSON的產生與讀取匯入

  • 28487
  • 0
  • .NET
  • 2013-01-18

[VB.NET] JSON的產生與讀取匯入

不詳細介紹JSON是什麼東東啦,反正就是一種資料交換或是傳遞的格式,還挺方便使用的唷。

 

範例大概狀況是這樣,我有兩個Table是一對多的狀況,就是一個訂單底下有很多Item項目,

主要任務就想把這兩個Table的資料產生成JSON的格式。

前置作業

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
這兩個要用的先Imports進來。

 

  1. 先建立Data Object
Public Class JsonDO

    Private A As Integer = 0
    Private B As String = ""
    Private C As Integer = 0
   
    Private item As Object


    Public Property pA() As Integer
        Get
            Return A
        End Get
        Set(ByVal value As Integer)
            A= value
        End Set
    End Property

    Public Property pB() As String
        Get
            Return B
        End Get
        Set(ByVal value As String)
            B= value
        End Set
    End Property

    Public Property pC() As Integer
        Get
            Return C
        End Get
        Set(ByVal value As Integer)
            C= value
        End Set
    End Property

    Public Property pItem() As Object
        Get
            Return item
        End Get
        Set(ByVal value As Object)
            item = value
        End Set
    End Property


End Class

2.把資料撈出來後塞進JsonDO,然後就可以產生JSON囉

 Dim Jstring As String
 Dim Jrecord As New JsonDO

'省略把資料塞進DO的Code唷~

'這段就是產生JSON的
Jstring = JsonConvert.SerializeObject(Jrecord)


3.抓取JSON中的值匯入

 '因為是範例所以還是先產生JSON字串,等等才可以讀取。
 Dim ImportJson As JObject
 ImportJson = JsonConvert.DeserializeObject(Of JObject)(Jstring)

 '這段意思就是我要讀取主檔資料表中Item欄位資料
 Dim JsonOB As Object
 JsonOB  = ImportJson .Item("pItem")
 
'如果要讀取第二層Item欄位中的細項可以這樣寫,那個 i 要給迴圈用的。
JsonOB  = ImportJson .Item("pItem").ElementAt(i).Item("pautoid")

'大致寫法就是這樣,有些Code有省略,請見諒^^。

產生出來的JSON可以到這裡去看唷 http://jsonviewer.stack.hu/

2012-5-15 上午 10-42-07

依我這個Demo的範例產生出來就是這樣。

 

因為要跟對方交換資料,所以就試了一下,對方給我的資料只要是照著我的DO那樣去產生的話,

這樣我就可以直接塞進去資料庫了^^,有不完善的地方還請大家多多指教。