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# – How to implement GetHashCode() and Equals()

The simplest way to implement GetHashCode() is to use the built-in System.HashCode.Combine() method and pick the properties you want to include. Let it do the work for you. Furthermore, the simplest way to implement Equals() is to use the is operator and compare all the properties. Here’s an example: Note: Use (Title, Year).GetHashCode() in versions … 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# – 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# – Check if a nullable bool is true

You can’t use nullable bools (bool?) exactly like regular bools, because they aren’t the same thing. When you try to use them like regular bools, you run into compiler errors and runtime exceptions. Instead, you have to explicitly compare the nullable bool with true/false. Here’s an example of checking if a nullable bool is true … Read more