Intellenum Help

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:

[ValueObject<float>(conversions: Conversions.None)] public readonly partial struct Celsius { }

Now, serialize an instance of Celsius to a JSON string using Newtonsoft.Json:

var weather = new { Summary = "Sunny and hot", TemperatureTodayInCelsius = Celsius.From(30) }; Console.WriteLine(JsonSerializer.Serialize(weather));

You'll see:

{"Summary":"Sunny and hot","TemperatureTodayInCelsius":{"Value":30}}

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.

[ValueObject<float>(Conversions.SystemTextJson)] public readonly partial struct Celsius { }

This outputs:

{ Summary = Sunny and hot, TemperatureTodayInCelsius = 30 }

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.

Last modified: 12 September 2024