Created
July 9, 2015 16:34
-
-
Save pcgeek86/23ad223dba5c36041e21 to your computer and use it in GitHub Desktop.
This Gist provides a suggested pattern for serializing / deserializing PowerShell v5 class instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Person { | |
| [ValidateNotNullOrEmpty()] | |
| [string] $FirstName; | |
| [ValidateNotNullOrEmpty()] | |
| [string] $LastName; | |
| [string] $Address; | |
| Person([string] $First, [string] $Last) { | |
| $this.FirstName = $First; | |
| $this.LastName = $Last; | |
| } | |
| [string] Serialize() { | |
| return $this | ConvertTo-Json; | |
| } | |
| static [Person] Deserialize([string] $Json) { | |
| $Deserialized = ConvertFrom-Json -InputObject $Json; | |
| $Person = [Person]::new($Deserialized.FirstName, $Deserialized.LastName); | |
| $Person.Address = $Deserialized.Address; | |
| return $Person; | |
| } | |
| } | |
| ### Instantiate the Person class | |
| $Person = [Person]::new('Trevor', 'Sullivan'); | |
| $Person.Address = '111 First Street'; | |
| ### Serialize the object instance | |
| $JsonText = $Person.Serialize(); | |
| ### Deserialize the object instance | |
| $Person = [Person]::Deserialize($JsonText); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment