PowerShell类设计优化:按需构建无空字段JSON数据结构
解决方案
核心思路
把原来预定义全量空结构的初始化逻辑,改成动态按需创建层级,用哈希表存储实际需要的节点,序列化时过滤空数组/空对象,只保留有实际内容的字段。
重构后的AllowListStructure类
class AllowListStructure { # 私有哈希表存储动态结构,初始为空 hidden [hashtable]$Structure = @{} # 创建指定的Root Hive(如"remove"),不存在则初始化 [void]AddRootHive([string]$hiveName) { if (-not $this.Structure.ContainsKey($hiveName)) { $this.Structure[$hiveName] = @{} } } # 在指定Root Hive下创建二级分支(如"Applications"),支持数组/对象两种类型 [void]AddBranch([string]$hiveName, [string]$branchName, [string]$type = "array") { # 先确保Root Hive存在 if (-not $this.Structure.ContainsKey($hiveName)) { $this.AddRootHive($hiveName) } # 初始化分支结构 if (-not $this.Structure[$hiveName].ContainsKey($branchName)) { $this.Structure[$hiveName][$branchName] = if ($type -eq "array") { @() } else { @{} } } } # 示例填充方法(保留你已有的填充逻辑,这里以添加移除类应用为例) [void]AddApplicationToRemove([PSObject]$appObject) { # 自动确保remove hive和Applications分支存在 $this.AddBranch("remove", "Applications") $this.Structure["remove"]["Applications"] += $appObject } # 转换为JSON,自动过滤空数组/空对象 [string]ToJson() { # 递归过滤空节点的辅助函数 function Filter-EmptyNodes { param([PSObject]$InputObj) $outputObj = [PSCustomObject]@{} foreach ($prop in $InputObj.PSObject.Properties) { $val = $prop.Value # 跳过空数组 if ($val -is [array] -and $val.Count -eq 0) { continue } # 跳过空对象 if ($val -is [PSObject] -and $val.PSObject.Properties.Count -eq 0) { continue } # 递归处理嵌套节点 if ($val -is [PSObject] -or $val -is [array]) { $filteredVal = Filter-EmptyNodes $val # 仅保留过滤后非空的节点 if (($filteredVal -is [array] -and $filteredVal.Count -gt 0) -or ($filteredVal -is [PSObject] -and $filteredVal.PSObject.Properties.Count -gt 0)) { $outputObj | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $filteredVal } } else { $outputObj | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $val } } return $outputObj } $baseObj = [PSCustomObject]$this.Structure $filteredObj = Filter-EmptyNodes $baseObj return $filteredObj | ConvertTo-Json -Depth 10 } }
使用示例
# 初始化空结构 $allowList = [AllowListStructure]::new() # 按需添加内容 $testApp = [PSCustomObject]@{ DisplayName = "Test Application" Version = "2.3.0" } $allowList.AddApplicationToRemove($testApp) # 生成JSON $allowList.ToJson()
输出效果
只会包含实际用到的字段,无空结构:
{ "remove": { "Applications": [ { "DisplayName": "Test Application", "Version": "2.3.0" } ] } }
关键改动说明
- 动态结构存储:用哈希表替代原来的预定义属性,初始为空,仅在调用创建方法时添加节点。
- 按需创建层级:
AddRootHive和AddBranch方法确保只有需要的层级才会被创建,避免预生成空结构。 - 空节点过滤:序列化前通过递归函数移除空数组、空对象,确保最终JSON只包含有实际内容的字段。
内容的提问来源于stack exchange,提问作者Douda
相关产品推荐
相关产品推荐

