From 634eef81c802f68fcd39f7a3d9e9a64ea04963e6 Mon Sep 17 00:00:00 2001 From: Jake Bolton Date: Sat, 20 Jan 2024 10:07:30 -0600 Subject: [PATCH] Text.Json notes --- .../Text.Json/System.Text.Json.CheatSheet.md | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/Pwsh/Modules/Text.Json/System.Text.Json.CheatSheet.md b/Pwsh/Modules/Text.Json/System.Text.Json.CheatSheet.md index b8ed641..014b278 100644 --- a/Pwsh/Modules/Text.Json/System.Text.Json.CheatSheet.md +++ b/Pwsh/Modules/Text.Json/System.Text.Json.CheatSheet.md @@ -1,9 +1,12 @@ - [To Import Namespace](#to-import-namespace) - [Serialization](#serialization) + - [ToString : `JsonSerializer::Serializer( o, type )`](#tostring--jsonserializerserializer-o-type-) - [Ignoring Properties : `JsonIgnoreAttribute`](#ignoring-properties--jsonignoreattribute) - [Ignore When null : `JsonIgnoreCondition`](#ignore-when-null--jsonignorecondition) - [Always Ignore](#always-ignore) - [Deserialization](#deserialization) +- [Other](#other) + - [AutoJson helper class](#autojson-helper-class) ## To Import Namespace @@ -17,8 +20,25 @@ $assembly = Add-type -AssemblyName System.Text.Json -PassThru -ea 'stop' ## Serialization +### ToString : `JsonSerializer::Serializer( o, type )` + +Using the `[type]` overload +```ps1 +class SimpleProcess { ... } +[SimpleProcess] $Obj = Get-process -PID $PID +[JsonSerializer]::Serialize( <# value: #> $Obj, <# jsonTypeInfo: #> [SimpleProcess]) +[JsonSerializer]::Serialize( <# value: #> $Obj, $Obj.GetType() ) +``` + ### Ignoring Properties : `JsonIgnoreAttribute` +| enum `JsonIgnoreCondition` | +| -------------------------- | +| Never | +| Always | +| WhenWritingDefault | +| WhenWritingNull | + #### Ignore When null : `JsonIgnoreCondition` ```ps1 @@ -44,3 +64,30 @@ class SimpleProcess { ## Deserialization + +## Other + +### AutoJson helper class + +```ps1 +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 ) +} +```