Parsing a nested value from a JSON string in .NET Core 3 without needing a DTO

.NET doesn’t use Newtonsoft by default anymore (since .NET Core 3.0). A lot of the examples online show how to use the new System.Text.Json namespace to extract values from JSON strings by deserializing the strings into full POCO classes (DTOs/ViewModels).

If you only want to extract the value of a particular property and don’t want the overhead of having to create a lot of nested classes, its very simple to extract values directly using the JsonDocument class.

For example if I have the following nested JSON structure (taken from Google PageSpeed API in case your curious) ..

PageSpeed nested JSON Structure


I want to extract the 0.82 score value I can just create a new instance of a JsonDocument and then chain a couple of GetProperty calls together.

How to read nested values in System.Text.Json

Of course to use GetProperty you need to be sure the property will always exist in your JSON as otherwise an exception will be thrown. If your not sure about this use TryGetProperty instead and check if you’ve successfully got an element before moving on…

TryGetProperty method

Leave a Reply

Your email address will not be published. Required fields are marked *