ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 3103|ตอบกลับ: 1

[VB.NET] การแสดงผลข้อมูลจาก JSON (ข้อมูลโควิด-19/ไทยและทั่วโลก) ลงในตารางกริด

[คัดลอกลิงก์]

308

กระทู้

499

โพสต์

6025

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
6025



รายละเอียดของเรื่อง JSON (JavaScript Object Notation) มีอยู่เยอะแยกมากมาย สามารถไปค้นหาใน Google ได้เลยครับ ... วันนี้แอดมินจะมานำเสนอโค้ดการแยกแยะข้อมูลของ JSON หรือที่มักจะเรียกกันว่า Deserialized เพื่อนำมาแสดงผลข้อมูลลงบนตารางกริด ซึ่งจำเป็นต้องใช้เครื่องมือตัวหนึ่งที่มีชื่อว่า NewtonSoft ซึ่งเป็นของฟรีครับผม สามารถดาวน์โหลดได้จากที่นี่ ...

Add References ... NewtonSoft.json ...


มาดูโค้ดฉบับเต็มกันเถอะ ...
  1. Public Class frmCovid19Json

  2.     Dim table As New DataTable

  3.     Private Sub frmCovid19Json_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  4.         Call GetCountry()
  5.     End Sub

  6.     Private Sub cmbCountry_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbCountry.SelectedIndexChanged
  7.         Dim url As String = String.Empty
  8.         Select Case cmbCountry.Text
  9.             Case "- All Countries Info -"
  10.                 url = "https://coronavirus-19-api.herokuapp.com/countries"
  11.             Case Else
  12.                 url = "https://coronavirus-19-api.herokuapp.com/countries/" & cmbCountry.Text
  13.         End Select
  14.         '//
  15.         Call GetDataJson(url)
  16.         'Call GetDataJsonObject(url)
  17.     End Sub

  18.     '// Deserialized JSON and return DataTable.
  19.     Public Function DeserializeDataTable(json As String) As DataTable
  20.         Dim dt As DataTable = TryCast(JsonConvert.DeserializeObject(json, (GetType(DataTable))), DataTable)
  21.         Return dt
  22.     End Function

  23.     Private Sub GetCountry()
  24.         Dim request As HttpWebRequest
  25.         Dim response As HttpWebResponse = Nothing
  26.         Dim reader As StreamReader
  27.         Dim url As String = "https://coronavirus-19-api.herokuapp.com/countries"
  28.         Try
  29.             request = DirectCast(WebRequest.Create(url), HttpWebRequest)
  30.             response = DirectCast(request.GetResponse(), HttpWebResponse)
  31.             reader = New StreamReader(response.GetResponseStream())
  32.             '//
  33.             Dim s As String
  34.             s = reader.ReadToEnd
  35.             '// Replace null value from JSON to zero.
  36.             s = s.Replace("null", "0")
  37.             Dim dt As DataTable
  38.             dt = DeserializeDataTable(s)
  39.             With cmbCountry
  40.                 .Items.Add("- All Countries Info -")
  41.             End With
  42.             table.Columns.Add("Country", GetType(String))
  43.             '// Add all country into ComboBox.
  44.             For i = 0 To dt.Rows.Count - 1
  45.                 cmbCountry.Items.Add(dt.Rows(i).Item(0).ToString)
  46.                 '// AutoComplete.
  47.                 table.Rows.Add(dt.Rows(i).Item(0).ToString)
  48.             Next
  49.             cmbCountry.SelectedIndex = 0
  50.             cmbCountry.Sorted = True

  51.             '// AutoComplete in TextBox Control.
  52.             Dim DataCollection As New AutoCompleteStringCollection()
  53.             DataCollection = GetAutoSourceCollection(table)
  54.             txtSearch.AutoCompleteCustomSource = DataCollection
  55.             txtSearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
  56.             txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource

  57.         Catch ex As Exception
  58.             MessageBox.Show(ex.Message)
  59.         End Try
  60.     End Sub

  61.     '// AutoComplete Collection
  62.     Private Function GetAutoSourceCollection(ByVal table As DataTable) As AutoCompleteStringCollection
  63.         Dim AutoSourceCollection As AutoCompleteStringCollection = New AutoCompleteStringCollection()
  64.         '// table from countries.
  65.         For Each row As DataRow In table.Rows
  66.             AutoSourceCollection.Add(row(0).ToString) '// Country data is the first column.
  67.         Next
  68.         Return AutoSourceCollection
  69.     End Function

  70.     '// Get JSON From URL.
  71.     Private Sub GetDataJson(ByVal url As String)
  72.         Dim request As HttpWebRequest
  73.         Dim response As HttpWebResponse = Nothing
  74.         Dim reader As StreamReader
  75.         Try
  76.             request = DirectCast(WebRequest.Create(url), HttpWebRequest)
  77.             response = DirectCast(request.GetResponse(), HttpWebResponse)
  78.             reader = New StreamReader(response.GetResponseStream())
  79.             Dim s As String
  80.             s = reader.ReadToEnd
  81.             s = s.Replace("null", "0")
  82.             Dim dt As DataTable
  83.             If Microsoft.VisualBasic.Left(s, 1) = "[" Then
  84.                 dt = DeserializeDataTable(s)
  85.             Else
  86.                 dt = DeserializeDataTable("[" & s & "]")
  87.             End If
  88.             dgvData.DataSource = dt
  89.             Call SetupGridView()
  90.         Catch ex As Exception
  91.             MessageBox.Show(ex.Message)
  92.         End Try
  93.     End Sub

  94.     '// Get JSON by Object From URL.
  95.     Private Sub GetDataJsonObject(ByVal url As String)
  96.         Dim request As HttpWebRequest
  97.         Dim response As HttpWebResponse = Nothing
  98.         Dim reader As StreamReader
  99.         Try
  100.             request = DirectCast(WebRequest.Create(url), HttpWebRequest)
  101.             response = DirectCast(request.GetResponse(), HttpWebResponse)
  102.             reader = New StreamReader(response.GetResponseStream())
  103.             Dim s As String
  104.             s = reader.ReadToEnd.Replace("null", "0")
  105.             If Microsoft.VisualBasic.Left(s, 1) <> "[" Then
  106.                 s = "[" & s & "]"
  107.             End If
  108.             '//
  109.             Dim res() = Newtonsoft.Json.JsonConvert.DeserializeObject(Of ItemsCovid())(s)
  110.             Dim dt As New DataTable
  111.             dt.Columns.Add("country", GetType(String))
  112.             dt.Columns.Add("cases")
  113.             dt.Columns.Add("todayCases")
  114.             dt.Columns.Add("deaths")
  115.             dt.Columns.Add("todayDeaths")
  116.             dt.Columns.Add("recovered")
  117.             dt.Columns.Add("active")
  118.             dt.Columns.Add("critical")
  119.             dt.Columns.Add("casesPerOneMillion", GetType(Integer))
  120.             For Each covid As ItemsCovid In res
  121.                 Dim dr As DataRow = dt.NewRow()
  122.                 If covid IsNot Nothing Then
  123.                     dr(0) = covid.country
  124.                     dr(1) = covid.cases
  125.                     dr(2) = covid.todayCases
  126.                     dr(3) = covid.deaths
  127.                     dr(4) = covid.todayDeaths
  128.                     dr(5) = covid.recovered
  129.                     dr(6) = covid.active
  130.                     dr(7) = covid.critical
  131.                     dr(8) = covid.casesPerOneMillion
  132.                 End If
  133.                 '// Add row.
  134.                 dt.Rows.Add(dr)
  135.             Next
  136.             dgvData.DataSource = dt
  137.             Call SetupGridView()
  138.         Catch ex As Exception
  139.             MessageBox.Show(ex.Message)
  140.         End Try
  141.     End Sub

  142.     Private Sub txtSearch_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtSearch.KeyDown
  143.         '// Press Enter
  144.         If e.KeyCode = Keys.Enter Then
  145.             e.Handled = True
  146.             '// Search for Country in DataTable.
  147.             Dim dv As DataView = New DataView(table)
  148.             dv.RowFilter = "Country = " & "'" & txtSearch.Text & "'"
  149.             If dv.Count > 0 Then
  150.                 Dim url As String = "https://coronavirus-19-api.herokuapp.com/countries/" & txtSearch.Text
  151.                 '// Second Methods
  152.                 Call GetDataJsonObject(url)
  153.             End If
  154.         End If
  155.     End Sub

  156.     Private Sub SetupGridView()
  157.         With dgvData
  158.             .RowHeadersVisible = True
  159.             .AllowUserToAddRows = False
  160.             .AllowUserToDeleteRows = False
  161.             .AllowUserToResizeRows = False
  162.             .MultiSelect = False
  163.             .SelectionMode = DataGridViewSelectionMode.CellSelect
  164.             .ReadOnly = True
  165.             '// Data rows
  166.             .Font = New Font("Tahoma", 9)
  167.             .RowTemplate.MinimumHeight = 27
  168.             .RowTemplate.Height = 27
  169.             '// Column Header
  170.             .ColumnHeadersHeight = 30
  171.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
  172.             '// Autosize Column
  173.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  174.             '// Header
  175.             With .ColumnHeadersDefaultCellStyle
  176.                 .BackColor = Color.Navy
  177.                 .ForeColor = Color.White
  178.                 .Font = New Font(dgvData.Font, FontStyle.Bold)
  179.             End With
  180.         End With
  181.         '/ todayDeaths
  182.         For i = 0 To dgvData.RowCount - 1
  183.             If dgvData.Rows(i).Cells(4).Value > 0 Then
  184.                 dgvData.Rows(i).Cells(4).Style.BackColor = Color.Red
  185.             End If
  186.         Next
  187.         For i = 1 To dgvData.ColumnCount - 1
  188.             dgvData.Columns(i).DefaultCellStyle.Format = "N0"
  189.             With dgvData.Columns(i)
  190.                 .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
  191.                 .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
  192.             End With
  193.         Next
  194.     End Sub

  195.     Private Sub frmCovid19Json_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  196.         Me.Dispose()
  197.         GC.SuppressFinalize(Me)
  198.         Application.Exit()
  199.     End Sub

  200. End Class

  201. '// "country":"Thailand","cases":599,"todayCases":188,"deaths":1,"todayDeaths":0,"recovered":44,"active":554,"critical":7,"casesPerOneMillion":9
  202. Public Class ItemsCovid
  203.     Public Property country As String
  204.     Public Property cases As Integer
  205.     Public Property todayCases As Integer
  206.     Public Property deaths As Integer
  207.     Public Property todayDeaths As Integer
  208.     Public Property recovered As Integer
  209.     Public Property active As Integer
  210.     Public Property critical As Integer
  211.     Public Property casesPerOneMillion As Integer
  212. End Class
คัดลอกไปที่คลิปบอร์ด

ดาวน์โหลดโค้ดฉบับเต็ม VB.NET (2010) ได้ที่นี่ ...

ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด

0

กระทู้

58

โพสต์

10

เครดิต

Member

Rank: 2

เครดิต
10
โพสต์ 2022-10-25 15:29:58 | ดูโพสต์ทั้งหมด

ขอบคุณครับ
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2024-4-19 04:58 , Processed in 0.191020 second(s), 4 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้