Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ninmonkey/b427d04031c6872b6e4637f23e9db2a3 to your computer and use it in GitHub Desktop.
Save ninmonkey/b427d04031c6872b6e4637f23e9db2a3 to your computer and use it in GitHub Desktop.
(wip sketch) Test: Auto add Attributes to Type Def for - System.Json.Text
#Requires -Version 7
using namespace System.Collections.Generic
using namespace System.Text
using namespace System.Text.Json
using namespace System.Text.Json.Serialization
$assembly = Add-type -AssemblyName System.Text.Json -PassThru -ea 'stop'
function AutoJson {
<#
.SYNOPSIS
Try one of the automatic methods
.notes
[System.Text.Json.JsonSerializer] has a ton of overloads
.LINK
https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer?view=net-8.0#methods
#>
param(
[Alias('InObj', 'In')]
[object] $Object,
# Without a type, it falls back to GetType()
[Alias('Tinfo', 'T')]
[type] $TypeInfo
)
if(-not $TypeInfo ) { $TypeInfo = $Object.GetType() }
[Text.Json.JsonSerializer]::Serialize( <# value: #> $Object, <# tinfo #> $TypeInfo )
}
class SomePS {
[string] $ProcessName
[int] $Id
[Serialization.JsonIgnoreAttribute()]
[Diagnostics.ProcessModuleCollection] $Modules
SomePS ( $src ) {
$this.ProcessName = $src.ProcessName
$this.Id = $Src.Id
$this.Modules = $Src.Modules
}
}
$hasModules = get-process | ? Modules | select -First 1
# [a] works
$hasModules -as [SomePS[]]
<# Out:
ProcessName Id Modules
----------- -- -------
ApplicationFrameHost 19636 {System.Diagnostics.ProcessModule (ApplicationFrameHost.exe), System.Diagnost ....
#>
$hasModules -as [SomePS[]] | %{ AutoJson -InObj $_ -TypeInfo ([SomePS]) }
<# Out:
{"ProcessName":"ApplicationFrameHost","Id":19636}
#>
# cool, typedata is constrained to derived types
$hasModules -as [SomePS[]] | %{ AutoJson -InObj $_ -TypeInfo ([System.Diagnostics.Process]) }
<# Out:
Exception calling "Serialize" with "2" argument(s): "The specified
type [System.Diagnostics.Process] must derive from the specific value's type [SomePS]."
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment