首页 > 解决方案 > 读取 JSON 文件 vb.net Newtonsoft

问题描述

我正在尝试使用 VB.NET 读取一个简单的 JSON 文件,但我真的找不到答案,因为无论我尝试什么都会出错。我正在使用 Newtonsoft.Json。我不确定是否需要使用 Dim jsonArray As JArray = JArray.Parse(json) 将其解析为 json 数组或作为对象。我想循环对象并将每个元素写入变量,以便将它们保存到数据库中。我已经在 javascript 中完成了这项工作,但 vb 让我失望了。

[  
   {  
      "Organization":"a",
      "Ref_ID":"33",
      "First":"Bob",
      "MI":"V",
      "Last":"Smith",
      "Suffix":""
   },
   {  
      "Organization":"a",
      "Ref_ID":"12",
      "First":"Mary",
      "MI":"",
      "Last":"Jones",
      "Suffix":""
   },
   {  
      "Organization":"Stony Brook",
      "Ref_ID":"74",
      "First":"Jonas",
      "MI":"S",
      "Last":"Green",
      "Suffix":""
   }
]

标签: vb.netjson.net

解决方案


您可以使用 Newtonsoft 轻松地将 JSON 转换为(类)对象列表。下面的示例使用具有单个文本框和按钮的表单。

Imports Newtonsoft.Json

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Const JSON As String = "[^   {^      'Organization':'a',^      'Ref_ID':'33',^      'First':'Bob',^      'MI':'V',^      'Last':'Smith',^      'Suffix':''^   },^   {^      'Organization':'a',^      'Ref_ID':'12',^      'First':'Mary',^      'MI':'',^      'Last':'Jones',^      'Suffix':''^   },^   {^      'Organization':'Stony Brook',^      'Ref_ID':'74',^      'First':'Jonas',^      'MI':'S',^      'Last':'Green',^      'Suffix':''^   }^]"
        txtJson.Text = JSON.Replace("^", vbCrLf).Replace("'", """")
    End Sub

    Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
        Try
            Dim xReturn As List(Of RandomPerson) = JsonConvert.DeserializeObject(Of List(Of RandomPerson))(txtJson.Text)

            Dim sMessage As String = ""

            For Each OnePerson As RandomPerson In xReturn
                sMessage &= OnePerson.Ref_ID & " // " & OnePerson.First & " // " & OnePerson.Last & vbCrLf
            Next OnePerson

            MessageBox.Show(Me, sMessage, "Done", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch Exp As Exception
            MessageBox.Show(Me, Exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub

End Class

'The class below was created by converting the example JSON into a C# class using: http://json2csharp.com/
'You can then convert the C# class into a VB.NET class by hand, or by using a tool like: http://www.carlosag.net/Tools/CodeTranslator/

Public Class RandomPerson
    Public Property Organization As String = ""
    Public Property Ref_ID As String = ""
    Public Property First As String = ""
    Public Property MI As String = ""
    Public Property Last As String = ""
    Public Property Suffix As String = ""
End Class

推荐阅读