Serializing to and from JSON
In this tutorial, we'll see how to serialize and deserialize value objects.
Vogen can automatically generate the code required for this. It supports System.Text.Json (STJ), Newtonsoft.Json (NSJ), and ServiceStack.Text
First, let's see what we get with no conversion generated. In a C# project that references Vogen, create the following type:
Now, serialize an instance of Celsius
to a JSON string using Newtonsoft.Json:
You'll see:
Note that the serializer has written the temperature as a composite object (Value:30
).
This isn't ideal as you probably want the primitive value written. And, Vogen won't be able to serialize that composite value back into a value object.
To get just the primitive value written, change Celcius
to this and rerun.
This outputs:
As well as treating the value object as a primitive, it also allows it to be deserialized back into a value object. Not that System.Text.Json is generated by default, so you could remove the Conversions
parameter altogether.
In this tutorial, we've seen how JSON is serialized if no conversions are specified, and then we've seen the difference that specifying the conversion makes.