Skip to main content

Smithy Document serialisation

The smithy4s-core module provides a smithy4s.Document datatype that is used in code-generation when document shapes are used in smithy. Document is effectively a JSON ADT, and can be easily converted to from other ADTs, such as the one provided by the Circe library.

Document also comes with its own Encoder and Decoder construct, for which instances can be derived for every datatype generated by Smithy4s.

import smithy4s.example.hello.Person
import smithy4s.Document

val personEncoder = Document.Encoder.fromSchema(Person.schema)
// personEncoder: Document.Encoder[Person] = smithy4s.Document$CachedEncoderCompilerImpl$$anon$1@1f7a620e
val personDocument = personEncoder.encode(Person(name = "John Doe"))
// personDocument: Document = DObject(
// value = Map("name" -> DString(value = "John Doe"))
// )

val personDecoder = Document.Decoder.fromSchema(Person.schema)
// personDecoder: Document.Decoder[Person] = smithy4s.Document$Decoder$$anon$2@51c04fab
val maybePerson = personDecoder.decode(personDocument)
// maybePerson: Either[smithy4s.codecs.PayloadError, Person] = Right(
// value = Person(name = "John Doe", town = None)
// )

By default, smithy4s Documents abide by the same semantics as smithy4s-json (see section below).

It is worth noting that, although Document is isomorphic to a JSON ADT, its .toString is not valid JSON. Likewise, the smithy4s-core module does not contain logic to parse JSON strings into Documents. In order to read/write Documents from/to JSON strings, you need the smithy4s-json module. The smithy4s.json.Json entry-point contains methods that work with Documents.