vb.net - 读取 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":""
}
]
解决方案
您可以使用 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
推荐阅读
- php - 来自 PHP 中许多表的嵌套 json 响应
- c# - MySQL 8:我应该能够写一个有效的 IEEE 754 浮点数并读回确切的值吗?
- angular - 如何在不打开页面的情况下运行 url?-角度
- python - 子进程将信息传递给 exe
- python - scipy.interpolate.make_interp_spline 给出“x 和 y 不兼容”错误
- java - 多个 Apache Flink 窗口验证
- android - 无法成功重建 android 项目 - 快照发布处理策略冲突
- react-native - ReactNative:无法解析 React Native CLI 配置:groovy.json.JsonException:无法确定当前字符
- c# - 如何在 C# 中为 2 编写正则表达式
- c++ - 在以下情况下如何解决未声明的变量