CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing JSON Deserialization of Nested Objects and Missing Properties

πŸ‘€ Views: 38 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
PowerShell JSON deserialization

Hey everyone, I'm running into an issue that's driving me crazy. I've tried everything I can think of but I'm learning this framework and I'm not sure how to approach I've been banging my head against this for hours..... I am working with PowerShell 7.3 and trying to deserialize a complex JSON string into a custom object. The JSON data represents user information with nested properties, but I keep working with issues where some of the properties are coming up as `$null` after deserialization. Here’s a sample of the JSON string I’m trying to parse: ```json { "User": { "Name": "John Doe", "Email": "john@example.com", "Address": { "Street": "123 Main St", "City": "Anytown" } } } ``` I defined a corresponding custom object type as follows: ```powershell class UserAddress { [string] $Street [string] $City } class User { [string] $Name [string] $Email [UserAddress] $Address } ``` When I attempt to deserialize the JSON, I use the `ConvertFrom-Json` cmdlet combined with `Select-Object` to create an instance of my custom object: ```powershell $jsonData = Get-Content -Path 'path/to/your/file.json' -Raw $userObject = $jsonData | ConvertFrom-Json | Select-Object -Property Name, Email, @{Name='Address';Expression={ [UserAddress]::new($_.Address.Street, $_.Address.City) }} ``` However, I keep getting this behavior message: ``` want to convert value "123 Main St" to type "UserAddress". behavior: "want to find an overload for "UserAddress" and the argument count: "2"" ``` It seems like the property is not set correctly, and as a result, I want to access the `Street` and `City` properties on the `$userObject.Address`. I’ve tried different approaches, including directly accessing the properties using `ConvertFrom-Json`, but the address still ends up being `$null`. Is there a better way to handle the deserialization of nested JSON properties in this case? Any advice or best practices would be greatly appreciated! The stack includes Powershell and several other technologies. What's the best practice here? My development environment is Linux. Any pointers in the right direction? I'm developing on Debian with Powershell. What are your experiences with this? This is my first time working with Powershell 3.9. Hoping someone can shed some light on this. I appreciate any insights!