You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang如何定义支持任意层级嵌套的动态struct反序列化JSON数据

解决方案

核心逻辑是利用 Go 结构体支持递归类型引用的特性,只定义一次通用的块设备结构即可适配无限层级嵌套。

1. 定义通用结构体

// BlockDevice 统一表示所有层级的块设备/分区,所有层级字段规则完全一致
type BlockDevice struct {
    DiskName   string        `json:"disk_name,omitempty"`
    Name       string        `json:"name,omitempty"` // 兼容JSON中部分设备仅返回name字段的场景
    Mountpoint interface{}   `json:"mountpoint"`
    Size       string        `json:"size"`
    Fstype     string        `json:"fstype,omitempty"`
    Partitions []BlockDevice `json:"partitions,omitempty"` // 嵌套自身类型切片,自动支持任意层级子分区
}

// 最外层JSON响应结构体
type DiskInfoResp struct {
    Blockdevices []BlockDevice `json:"blockdevices"`
}

2. 反序列化使用示例

import "encoding/json"

func ParseDiskInfo(jsonData []byte) (DiskInfoResp, error) {
    var resp DiskInfoResp
    err := json.Unmarshal(jsonData, &resp)
    return resp, err
}

3. 补充说明

  • 该方案不需要提前预设嵌套层级,encoding/json 库会自动递归解析所有层级的 partitions 字段,嵌套10层、100层都可以正常适配
  • 如果需要遍历所有分区,写递归函数即可实现:
func PrintAllDevices(devs []BlockDevice) {
    for _, d := range devs {
        // 自定义处理当前设备的逻辑
        println("设备名:", d.DiskName, d.Name, "大小:", d.Size)
        // 递归遍历子分区
        if len(d.Partitions) > 0 {
            PrintAllDevices(d.Partitions)
        }
    }
}

内容的提问来源于stack exchange,提问作者Kashif Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 04:15:04