C# – Deserialize JSON to a dictionary

I’ll show examples of how to deserialize JSON to dictionaries in different scenarios. Deserializing to Dictionary<string, string> When your JSON object has properties with simple string values (as opposed to nested objects), you can deserialize to Dictionary<string, string>. Here’s an example. Consider the following simple JSON object: Note: In all examples, I’ll show the pretty-printed … Read more

C# – Serialize a dictionary to JSON

When you want to convert a dictionary to a JSON string, you can use the built-in JsonSerializer (from System.Text.Json) to serialize the dictionary. Here’s an example: Note: This is passing in WriteIndented=true to pretty print the JSON string for readability. This serializes the dictionary to a JSON string with the following format: I’ll show more … Read more

C# – Convert JSON to an object

Converting a JSON string to an object is referred to as deserialization. You can do this with a JSON serializer. There are two primary options: I’ll show examples by deserializing the following Movie JSON to a Movie object: Movie JSON: Movie class (properties match JSON): Using JsonSerializer.Deserialize() (in System.Text.Json) To deserialize with the built-in JsonSerializer.Deserialize(), … Read more

C# – Serialize to JSON in alphabetical order

There are two ways to serialize an object’s properties to JSON in alphabetical order using System.Text.Json: I’ll show how to do these two options below. Option 1 – Manually alphabetize with JsonPropertyOrder You can specify the exact serialization ordering by using the JsonPropertyOrder attribute. Therefore, to serialize in alphabetical order, first arrange the properties in … Read more

C# – Serialize and deserialize a multidimensional array to JSON

System.Text.Json doesn’t support serializing / deserializing multidimensional arrays. When you try, it throws an exception like this – System.NotSupportedException: The type ‘System.Int[,] is not supported. You have three options: In this article, I’ll show an example of how to create a custom JsonConverter that handles multidimensional arrays. In this example, I’ll specifically show how to … Read more

C# – JSON value could not be converted to System.String

When you send a request to ASP.NET with a JSON body, you get the following exception: System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1. You can’t deserialize JSON to a string. You’re either using a string parameter with [FromBody] or your model has a string … Read more

C# – JSON deserializer returns null properties

Let’s say you have the following JSON: When you go to deserialize it, you notice that all or some of its properties are null (or default for value types): This outputs the following (because person.Name is null and person.Pets is 0): The data is definitely there, so why did it set these properties to null … Read more

C# – Ignore null properties during JSON serialization

By default, null properties are included during JSON serialization like this: There are two ways to ignore null properties: In this article, I’ll show examples of these two ways to ignore null properties. I’ll show how to do it with System.Text.Json and Newtonsoft. Ignore null properties with System.Text.Json Use JsonIgnoreCondition.WhenWritingNull to ignore null properties. You … Read more

C# – How to use JsonNode to read, write, and modify JSON

When you don’t want to create classes for JSON (de)serialization, one option is to use JsonNode. This allows you work with JSON as a mutable DOM that consists of JsonNode objects (JsonObject, JsonArray, JsonValue). You can use it to read, write, and modify JSON. Here’s an example. Let’s say you have the following JSON that … Read more

C# – How to read problem details JSON with HttpClient

Problem details (RFC7807) is a standardized error response format that has a Content-Type of application/problem+json, an error response code (i.e. 400 – Bad Request), and has a response body that looks like this: This can be extended to include any number of properties. The example shown above comes from the default way ASP.NET Core returns … Read more

C# – JSON object contains a trailing comma at the end which is not supported

Problem When you deserialize JSON with a “trailing comma”, you get the following error: The JSON object contains a trailing comma at the end which is not supported in this mode. Change the reader options. JSON properties are separated with commas. A trailing comma is one that has no properties after it. Here’s an example … Read more

C# – Deserialize JSON using different property names

When JSON property names and class property names are different, and you can’t just change the names to match, you have three options: These options affect both deserialization and serialization. Let’s say you have the following JSON with camel-cased property names: Here’s an example of using the JsonPropertyName attribute: Note: The Newtonsoft equivalent is [JsonProperty(“title”)] … Read more

C# – Deserialize JSON with a specific constructor

When your class has multiple constructors, you can use the JsonConstructor attribute to specify which constructor to use during deserialization. Here’s an example. The Person class has two constructors. I put the JsonConstructor attribute on one of the constructors: Note: JsonConstructor for System.Text.Json was added in .NET 5. Now deserialize a JSON string to the … Read more

C# – Deserialize JSON to a derived type

The simplest way to deserialize JSON to a derived type is to put the type name in the JSON string. Then during deserialization, match the type name property against a set of known derived types and deserialize to the target type. System.Text.Json doesn’t have this functionality out of the box. That’s because there’s a known … Read more

C# – Examples of using JsonDocument to read JSON

You can use the JsonDocument class when you want to read and process JSON without having to deserialize the whole thing to an object. For example, let’s say you have the following JSON object representing wind variables: Now let’s say you’re only interested in the wind speed. Instead of having to deserialize this into a … Read more

C# – Populate an existing object with JSON

Normally when you’re working with JSON, you deserialize it to a target type and get back an initialized and fully populated object. How about if you need to initialize an object yourself, and then populate it with JSON later? For example, let’s say you want to load the following JSON array into a case-insensitive HashSet: … Read more

C# – How to ignore JSON deserialization errors

One error during JSON deserialization can cause the whole process to fail. Consider the following JSON. The second object has invalid data (can’t convert string to int), which will result in deserialization failing: With Newtonsoft, you can choose to ignore deserialization errors. To do that, pass in an error handling lambda in the settings: This … Read more

C# – Deserialize a JSON array to a list

When you’re working with a JSON array, you can deserialize it to a list like this: This deserializes all of the objects in the JSON array into a List<Movie>. You can use this list object like usual. Note: All examples will use System.Collections.Generic and System.Text.Json. I’ll exclude the using statements for brevity. Example – JSON … Read more

C# – Deserialize JSON as a stream

Here’s an example of deserializing JSON from a file as a stream with System.Text.Json: Stream deserialization has three main benefits: In this article, I’ll go into details about these benefits and show a few other stream serialization scenarios. Benefits of deserializing as a stream Performance There are two ways to deserialize JSON: Deserializing a stream … Read more

C# – How to use JsonExtensionData

Use the JsonExtensionData attribute (in System.Text.Json) to deserialize properties that aren’t part of the class. Without this, JSON fields that don’t match a property are simply ignored and the returned object will have null properties. Here’s an example of adding this attribute to a dictionary property: Now when you deserialize JSON to this Person class, … Read more

C# – Property order with System.Text.Json

You can use the JsonPropertyOrder attribute to control the order that properties get serialized. You specify the order as an integer, and it serializes the properties in ascending order. Here’s an example: Note: Properties have a default order value of 0. Now serialize an object to JSON: This generates the following JSON: Notice the properties … Read more

C# – How to use JsonConverterAttribute

You can use JsonConverterAttribute (from System.Text.Json) to apply a specific JsonConverter to a property. Apply this attribute on a property and specify the JsonConverter type to use, like this: In this example, it’s applying ExpirationDateConverter (a custom JSON converter) to handle the ExpirationDate. For reference, here’s ExpirationDateConverter’s definition: Now serialize the object to JSON: Here’s … Read more

C# – Changing the JSON serialization date format

When you serialize a date with System.Text.Json, it uses the standard ISO-8601 date format (ex: “2022-01-31T13:15:05.2151663-05:00”). Internally, it uses the built-in DateTimeConverter class for handling DateTime, which doesn’t give you a way to change the date format. To change the date format, you have to create a custom JSON converter and pass it in: This … Read more

C# – Convert an object to JSON

Converting an object to a JSON string is referred to as serialization. The best way to do serialization is by using a good JSON serializer. There are two primary options: I’ll show examples of both options below. Using JsonSerializer.Serialize() (in the built-in System.Text.Json) Here’s an example of using the built-in JsonSerializer.Serialize() (in System.Text.Json) to convert … Read more

C# – How to programmatically update the User Secrets file

User Secrets are stored in secrets.json. This file is specific to your application. Once you know the path of secrets.json, you can load and update it. Here’s an example of how to update secrets.json programmatically: Note: 1) For brevity, this isn’t showing all using statements. 2) This is using Newtonsoft because it’s better than System.Text.Json … Read more