Closed AArnott closed 3 hours ago
Hmmm... Maybe this already exists as a sample I can build off of:
@eiriktsarpalis I'm a bit surprised that you didn't use the visitor pattern for the JSON schema construction. Any particular reason?
I'm a bit surprised that you didn't use the visitor pattern for the JSON schema construction. Any particular reason?
The primary purpose of the visitor is unwrapping type information of the type graph via its generic parameters. If there's no need for this (e.g. because property accessors or constructors aren't necessary) then using a simple pattern match/switch statement should suffice to perform the traversal.
I got really far with your approach. Now I'm experimenting with a retrofit wherein I ask each MessagePackConverter<T>
to contribute its schema fragment. It'll better support custom converters and is more likely to be kept up-to-date than if we have just one class with 'all the answers' built-in.
What type do these converters return? JsonNode
presumably?
For the schema? They return JsonObject
.
There should be an API that can take an
ITypeShape<T>
and export a schema.This could perhaps be a feature of PolyType instead of MessagePack, since this use case applies more broadly and for the most part the result would be the same. However, Nerdbank.MessagePack adds attributes that can alter the schema, or runtime options like name policy may alter it. (CC: @eiriktsarpalis)
Another open question is what should the format of the schema be? Should it be machine-parseable? If so, it could perhaps be the basis for other languages to import the schema to recreate type definitions in their native language to support interop. Maybe standardize on JSON Schema?
Example
Consider this set of types:
This would render as the following language-neutral schema, assuming a call to
GenerateSchema<Tree>()
:This assumes the object graph is serialized with maps of properties. When an object is serialized as an array of values instead, the schema ought to indicate that. For example:
Renders as the following schema:
If C# properties/types are annotated with
[Description("...")]
we may want to include that string in the schema. JSON Schema for example has room to store such a description.