我有一个与REST服务交互的C#Cmdlet,将JSON反序列化为动态对象(ExpandoObject
)。当一个expando传递给WriteObject
时,它会被作为字典写入管道,所以我将它转换为PSObject
,以便使Select-Object
之类的属性可以访问它:
protected void WriteDynamicObject(dynamic o)
{
var psObject = ConvertToPSObject(o);
WriteObject(psObject);
}
private static PSObject ConvertToPSObject(dynamic o)
{
var d = o as IDictionary<string, object>;
Debug.Assert(d != null);
var record = new PSObject();
foreach (var kvp in d)
{
// if the value is itself an expando, convert it recursively
var value = kvp.Value is ExpandoObject ? ConvertToPSObject(kvp.Value) : kvp.Value;
record.Properties.Add(new PSNoteProperty(kvp.Key, value));
}
return record;
}
这适用于所有动态对象的属性,除了属于复杂类型的属性。上面的代码将递归地将非标量子对象转换为PSObject实例。例如,此JSON结果的projectTeam属性将转换为PSOBject:
{
"kind": "storage#bucketAccessControl",
"role": "OWNER",
"projectTeam": {
"projectNumber": "930617506804",
"team": "owners"
},
"etag": "CAE="
}
当我尝试从管道中选择projectTeam
属性时,我得到一个字符串表示,并且无法选择该子对象的属性:
projectTeam
-----------
@{projectNumber=930617506804; team=owners}
@{projectNumber=930617506804; team=editors}
@{projectNumber=930617506804; team=viewers}
我想我希望能够选择或以其他方式导航对象层次结构。 PSObjects
是否基本上是一组平面的名称值对,还是它们代表一个对象层次结构?如果是这样,如何表示嵌套对象,使其属性可选,或者是否需要展平对象层次结构?