MST
星途 面试题库

面试题:Visual Basic处理复杂嵌套JSON结构解析

有一个复杂嵌套的JSON字符串 '{"person":{"name":"Alice","hobbies":["reading","painting"],"address":{"city":"New York","zip":10001}}}',请使用Visual Basic编写程序,解析出这个人的爱好列表和所在城市,并展示如何处理可能出现的JSON格式错误。
15.1万 热度难度
编程语言Visual Basic

知识考点

AI 面试

面试题答案

一键面试

以下是使用Visual Basic解析该JSON字符串并处理格式错误的代码示例:

Imports System
Imports System.IO
Imports System.Text.Json

Module Module1
    Sub Main()
        Dim jsonString As String = "{""person"":{""name"":""Alice"",""hobbies"":[""reading"",""painting""],""address"":{""city"":""New York"",""zip"":10001}}}"
        Try
            Dim options As New JsonSerializerOptions With {.PropertyNameCaseInsensitive = True}
            Dim root As JsonElement = JsonSerializer.Deserialize(Of JsonElement)(jsonString, options)
            Dim person As JsonElement = root.GetProperty("person")
            Dim hobbies As JsonElement = person.GetProperty("hobbies")
            Dim hobbyList As New List(Of String)
            For Each hobby In hobbies.EnumerateArray()
                hobbyList.Add(hobby.GetString())
            Next
            Dim address As JsonElement = person.GetProperty("address")
            Dim city As String = address.GetProperty("city").GetString()
            Console.WriteLine("爱好列表:")
            For Each hobby In hobbyList
                Console.WriteLine(hobby)
            Next
            Console.WriteLine($"所在城市: {city}")
        Catch ex As JsonException
            Console.WriteLine($"JSON格式错误: {ex.Message}")
        End Try
    End Sub
End Module

在上述代码中:

  1. 使用System.Text.Json命名空间来处理JSON。
  2. 通过JsonSerializer.Deserialize方法将JSON字符串反序列化为JsonElement
  3. JsonElement中获取所需的属性值,如hobbiescity
  4. 使用Try...Catch块捕获可能的JsonException,以处理JSON格式错误。

注意:确保项目引用了System.Text.Json库,在较新的Visual Basic版本中通常会默认包含。如果是旧版本,可能需要手动添加引用。