In a perfect world, you’d have to write zero JsonConverter
classes, as all JSON data would serialize and deserialize as expected. Unfortunately, we live in a world where folks make bespoke formatting decisions that can boggle the mind. For folks using System.Text.Json
, you’ll likely have to write a JsonCoverter
to deal with these choices. When writing converters, you’ll want a test suite to ensure you’ve caught all the edge cases and to limit exceptions.
In this post, I’ll provide extension methods that make it a breeze to test any JsonConverter
and a bonus class that makes it simpler to deal with double-quoting values.
The JSON Converter Example
Before we see the extension methods in action, let’s derive a JsonConverter
definition.
Every JsonConverter
has a Read
and Write
method. The read method allows you to process the appropriate token into the destination target. In this example, we’re taking a string with a particular date and time format and converting it into a DateTime
instance. For the Write
method, we use the same format to write the string value to the UTF8JsonWriter
instance. Implementing either method depends on your use case and whether you’re serializing, deserializing, or performing both actions.
Let’s get to what a test looks like for this converter.
Writing Tests for Json Converters
Let’s take a look at the “ideal” test for executing the Read
and Write
methods. Note, these are extension methods, and the code is not calling the methods directly.
Oooo, so lovely. How did I accomplish such sweet tests? Well, it’s these extension methods.
These extensions have Read
, TryRead
, Write
, and TryWrite
methods to reduce the boilerplate code you might add to your tests.
Double Quoting JSON Tokens
You may have noticed in the tests above that tokens need to be double-quoted. This can be unpleasant, especially when you tweak values as you write more tests. That’s why I created a Quote
class that utilized explicit
and implicit
cast operators to double-quote any value.
Let’s see it in action.
Now it should be easier to manage your values without escaping any double quotes.
Conclusion
The JsonConverter
class is a necessary part of working with System.Text.Json
and writing tests around your implementations is a must. I hope these extension methods make it easier for you and your team to maintain your implementations.
Cheers. Thanks for reading and sharing my blog posts with friends and colleagues.