3. Let's Serialize

You can encode and decode objects using the global dogs variable. All default serializer expand the dogs engine instance with <format>Encode and <format>Decode methods taking a required generic type argument and a value to encode or decode. This could look something like this:

  var encoded = dogs.jsonEncode<Person>(person); // Returns a string
  var decoded = dogs.jsonDecode<Person>(encoded); // Returns a 'Person'

You can also encode and decode list, sets, and other iterables using the respective methods:

  var encoded = dogs.jsonEncodeList<Person>([personA,personB]);
  var decoded = dogs.jsonDecodeList<Person>(encoded);

Don't forget to explicitly specify the type of the encoded value using the generic type argument of the convert method. Type Inference can work in some cases, but when it doesn't, it leads to hard-to-diagnose bugs as the code is technically valid.

Last updated