面试题答案
一键面试以下是使用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
在上述代码中:
- 使用
System.Text.Json
命名空间来处理JSON。 - 通过
JsonSerializer.Deserialize
方法将JSON字符串反序列化为JsonElement
。 - 从
JsonElement
中获取所需的属性值,如hobbies
和city
。 - 使用
Try...Catch
块捕获可能的JsonException
,以处理JSON格式错误。
注意:确保项目引用了System.Text.Json
库,在较新的Visual Basic版本中通常会默认包含。如果是旧版本,可能需要手动添加引用。