Skip to content

Commit

Permalink
Text.Json notes
Browse files Browse the repository at this point in the history
  • Loading branch information
ninmonkey committed Jan 20, 2024
1 parent d15ca5f commit 634eef8
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Pwsh/Modules/Text.Json/System.Text.Json.CheatSheet.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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
Expand All @@ -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 )
}
```

0 comments on commit 634eef8

Please sign in to comment.