#Using Text.JSON
5 messages · Page 1 of 1 (latest)
JsonConverter<> won't be possible to implement in pure PowerShell script as it uses ref structs
We're attempting to deserialize a property that is a hash table, which by default will deserialize to this JsonElement. Presumably I'm stuck fixing that in post where in Newtonsoft I could use a converter
I don't know enough about STJ to know if there is a different route you could take, but I can tell you if you are required to implement a method that utilizes a ref struct, that's gonna be a no go
C# or sticking with newtonsoft are likely the two options yeah
Check out this page for migration info https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft?source=recommendations&pivots=dotnet-8-0
I have a couple of pure-pwsh examples where my class is basically a record pattern:
https://github.com/ninmonkey/TinyBits/tree/main/pwsh/Text.Json/basics
Sometimes all you need are a JsonAttributes on your record, to give it hints to auto coerce for you.
This route doesn't require [ref] structs
The screenshot is from: https://github.com/ninmonkey/TinyBits/blob/main/pwsh/Text.Json/basics/Using_UserDefinedEnums.ps1
For the pwsh version: the basic invocation is [de]serialize( object, type )
[Text.Json.JsonSerializer]::Deserialize( '7', [ConsoleColor] ) # output -is [ConsoleColor]
Using a custom class:
class User {
[Int] $Id = 0
[string] $Name = 'anonymous'
}
$bob = [User]@{ Name = 'bob' }
$json = [Text.Json.JsonSerializer]::Serialize( $bob, [User] )
# out: {"Id":0,"Name":"bob"}
$round_trip = [Text.Json.JsonSerializer]::Deserialize( $json, [User] )
$round_trip -is [User] # out: True
Note: $round_trip is not a [PSCO]
Here's an older gist using these field attributes
[JsonIgnoreAttribute( Condition = [JsonIgnoreCondition]::WhenWritingNull ) ]
[Serialization.JsonIgnoreAttribute()]
#fringe message