【问题标题】:How to parse values in JSON file and return the values in a MessageBox?如何解析 JSON 文件中的值并返回 MessageBox 中的值?
【发布时间】:2019-05-10 07:52:29
【问题描述】:

我正在使用 vb.net 开发一个 Windows 窗体应用程序,其中用户在文本框中输入一个 ID,然后在 MessageBox 中返回一个值。

我现在遇到的问题是如何解析文本框中的值,然后如何将其与 JSON 文件本身中的现有值进行比较。

这是Button类的代码:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    myFiles = MyFileObjects.Deserialize(File.ReadAllText("[FilePath]"))
    Dim json = MyFileObjects.Serialize(myFiles)
    File.WriteAllText("[FilePath]", json)
End Sub

这是公共类的模块:

Public Class MyFileObjects
    Public Class MyFile
        <JsonProperty("filename")>
        Public Property FileName As String
        <JsonProperty("title")>
        Public Property Title As String
        <JsonProperty("type")>
        Public Property Type As String
    End Class

    Public Shared Function Serialize(myFiles As List(Of MyFile)) As String
        Return JsonConvert.SerializeObject(myFiles)
    End Function

    Public Shared Function Deserialize(json As String) As List(Of MyFile)
        Return JsonConvert.DeserializeObject(Of List(Of MyFile))(json)
    End Function
End Class

这是用于文本框的:

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
    If e.KeyValue = Keys.Enter Then
        Dim selectedItem = myFiles.Find(Function(f) f.FileName.Equals(TextBox1.Text))
        If selectedItem IsNot Nothing Then
            MessageBox.Show(selectedItem.Title)
        End If
    End If
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
    TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
    TextBox1.AutoCompleteCustomSource.AddRange(myFiles.Select(Function(f) f.FileName).ToArray())
End Sub

这是我的 JSON 的内容:

[
  {
    "filename": "123.xml",
    "title": "Hello",
    "type": "PU"
  },
  {
    "filename": "456.xml",
    "title": "World",
    "type": "PU"
  },
  {
    "filename": "258.xml",
    "title": "Test",
    "type": "PU"
  }
]

用户应在文本框字段中搜索datafilename,并在消息框中显示“标题”。现在我不知道下一步该做什么。

【问题讨论】:

  • 我正计划向文本框添加自动完成功能,但我不知道是否可以将这些值存储在 json 文件中,而不是在自动完成源中手动输入列表.然后,用户可以从包含“文件名”值以及与“标题”值匹配的列表中选择一个。最后,“标题”值将显示在消息框中。当我想从 json 文件中获取值时,您认为可以这样做吗?

标签: json vb.net winforms json.net


【解决方案1】:

您的JSON 是一个简单对象的列表/数组。可以使用单个 Class 对象对其进行反序列化/序列化:
(一个名为 myFiles 的私有字段用于包含反序列化的对象)

Private myFiles As List(Of MyFileObjects.MyFile)

Public Class MyFileObjects
    Public Class MyFile
        <JsonProperty("filename")>
        Public Property FileName As String
        <JsonProperty("Title")>
        Public Property Title As String
        <JsonProperty("type")>
        Public Property Type As String
    End Class

    Public Shared Function Serialize(myFiles As List(Of MyFile)) As String
        Return JsonConvert.SerializeObject(myFiles)
    End Function
    Public Shared Function Deserialize(json As String) As List(Of MyFile)
        Return JsonConvert.DeserializeObject(Of List(Of MyFile))(json)
    End Function
End Class

注意我添加了:

  • &lt;JsonProperty()&gt; 属性:这允许在序列化列表/数组时修改类属性的名称,同时保留原始JSON 中的名称。当JSON 包含语言中的保留关键字(例如,operatortype 等)时,它非常有用
  • 两种方法允许通过一次调用反序列化/序列化JSON

JSON反序列化为List(Of MyFileObjects.MyFile):

myFiles = MyFileObjects.Deserialize(File.ReadAllText("[File Path]"))

List(Of MyFileObjects.MyFile) 序列化回JSON

Dim json = MyFileObjects.Serialize(myFiles)

创建一个 TextBox 的 AutoCompleteCustomSource 以启用其自动完成功能:
AutoCompleteModeAutoCompleteSource 属性可以在表单的设计器中预先设置)

TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
TextBox1.AutoCompleteCustomSource.AddRange(myFiles.Select(Function(f) f.FileName).ToArray())

当用户使用自动完成功能选择一个项目时显示一个消息框:

请注意,当从自动完成列表中选择项目时,自动完成功能会在所选文本中添加 Key.Enter。您无需按 Enter 键。

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
    If e.KeyValue = Keys.Enter Then
        Dim selectedItem = myFiles.Find(Function(f) f.FileName.Equals(TextBox1.Text))
        If selectedItem IsNot Nothing Then
            MessageBox.Show(selectedItem.Title)
        End If
    End If
End Sub

将一个Item添加到对象列表中,然后序列化并保存JSON

myFiles.Add(New MyFileObjects.MyFile() With {
    .FileName = "500.xml",
    .Title = "Title 500",
    .Type = "PU"
})

Dim json = MyFileObjects.Serialize(myFiles)
File.WriteAllText("[File Path]", json)

完整代码:

Public Class Form1

    Private myFiles As List(Of MyFileObjects.MyFile)
    Private jsonPath As String = String.Empty

    Public Class MyFileObjects
        Public Class MyFile
            <JsonProperty("filename")>
            Public Property FileName As String
            <JsonProperty("Title")>
            Public Property Title As String
            <JsonProperty("type")>
            Public Property Type As String
        End Class

        Public Shared Function Serialize(myFiles As List(Of MyFile)) As String
            Return JsonConvert.SerializeObject(myFiles, Formatting.Indented)
        End Function

        Public Shared Function Deserialize(json As String) As List(Of MyFile)
            Return JsonConvert.DeserializeObject(Of List(Of MyFile))(json)
        End Function
    End Class

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        jsonPath = "[Insert your JSON Path here]"
        myFiles = LoadJSON(jsonPath)
        TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
        TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
        TextBox1.AutoCompleteCustomSource.AddRange(myFiles.Select(Function(f) f.FileName).ToArray())
    End Sub

    Private Function LoadJSON(JSONPath As String) As List(Of MyFileObjects.MyFile)
        Return MyFileObjects.Deserialize(File.ReadAllText(JSONPath))
    End Function

    Private Sub SaveJSON(filePath As String, objects As List(Of MyFileObjects.MyFile))
        File.WriteAllText(filePath, MyFileObjects.Serialize(objects))
    End Sub

    Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyValue = Keys.Enter Then
            Dim selectedItem = myFiles.Find(Function(f) f.FileName.Equals(TextBox1.Text))
            If selectedItem IsNot Nothing Then
                MessageBox.Show(selectedItem.Title)
            End If
        End If
    End Sub
End Class

Private Sub buttonSaveJson_Click(sender As Object, e As EventArgs) Handles buttonSaveJson.Click
    SaveJSON(jsonPath, myFiles)
End Sub

【讨论】:

  • 这里的错误是“e.KeyValue 不是 system.eventargs 的成员”。这是否意味着我没有包含任何与之相关的命名空间元素?
  • 您订阅了错误的事件。 TextBox.KeyDown 事件提供 KeyEventArgs,而不是 EventArgs。检查您的代码。
  • 我开始运行它并在TextBox中输入一个字母然后它显示:_{“Value cannot be null. Parameter name: source”} _
  • 发布您现在使用的代码(更新您的问题)。你没有按照我在这里写的。如果我看不到您的实际代码是什么,我无法告诉您它有什么问题。如果您不知道如何更新您的问题,请点击下方的 edit 链接。
  • 你没有在我能看到的任何地方定义myFiles。我从未使用过TextBox.TextChanged。您绝对不想在该事件中创建 CustomSource。我将把不同的部分放在一个新的编辑中。尝试按照说明插入所有内容。
猜你喜欢
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
相关资源
最近更新 更多