在VB.NET中创建嵌套JSON对象的技术求助
修正VB.NET中嵌套JSON对象的类结构问题
问题的核心是当前类结构没有匹配期望的嵌套层级——carlist应该是包含attributes数组的对象集合,而非直接的attributes列表。以下是具体修改方案:
修改后的完整代码
类定义部分
Public Class Attribute Public Property key As String Public Property value As String End Class Public Class Car Public Property attributes As List(Of Attribute) End Class Public Class GetCars Public Property carlist As List(Of Car) Public Property driver As String Public Property year As Integer Public Property color As String End Class
实例化与序列化部分
' 创建属性列表 Dim attrs As New List(Of Attribute) From { New Attribute() With {.key = "MAKE", .value = "Honda"}, New Attribute() With {.key = "MODEL", .value = "S2000"} } ' 创建单个Car对象,嵌套属性列表 Dim carItem As New Car() With {.attributes = attrs} ' 组装最终的GetCars实例 Dim carOutput As New GetCars() With { .carlist = New List(Of Car) From {carItem}, .driver = "test", .year = 2001, .color = "test" } ' 序列化生成格式化的JSON Dim JSONString = System.Text.Json.JsonSerializer.Serialize(carOutput, New JsonSerializerOptions() With {.WriteIndented = True})
关键修改说明
- 新增
Car类:作为carlist数组的元素类型,专门承载attributes数组,实现期望的嵌套层级。 - 调整
GetCars的carlist类型:从List(Of Attribute)改为List(Of Car),匹配JSON中carlist是对象数组的结构。 - 修正代码错误:统一类名拼写(原代码类名
attributes与实例化时的attribute不一致,改为Attribute)、修复非法变量名(car output改为carOutput)。 - 优化序列化配置:移除不必要的
IncludeFields(使用属性而非字段),添加.WriteIndented = True生成格式化的JSON。
修改后生成的JSON输出
{ "carlist": [ { "attributes": [ { "key": "MAKE", "value": "Honda" }, { "key": "MODEL", "value": "S2000" } ] } ], "driver": "test", "year": 2001, "color": "test" }
内容的提问来源于stack exchange,提问作者CavFife
相关产品推荐
相关产品推荐

