Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override JsonSchema.toString() #42

Closed
martinp999 opened this issue Nov 25, 2020 · 2 comments
Closed

Override JsonSchema.toString() #42

martinp999 opened this issue Nov 25, 2020 · 2 comments
Labels
question Further information is requested

Comments

@martinp999
Copy link

Firstly, thank you for such an awesome library and excellent documentation.

I installed it yesterday and am experimenting with adding a reference to a schema using the fluent approach (it would also be good to include a more fully fleshed out example on https://gregsdennis.github.io/json-everything/usage/schema/references.html that uses the fluent approach).

I think I have it right but it would be really good to see the generated schema as JSON. Could you override JsonSchema.toString() so that it outputs something that JsonSchema.FromText(content) could load?

@gregsdennis gregsdennis added the question Further information is requested label Nov 25, 2020
@gregsdennis
Copy link
Collaborator

gregsdennis commented Nov 26, 2020

Thank you for the compliment. I'm glad that the library is working well for you.

Converting a JsonSchema to a string isn't something that really fits in a .ToString() method. It requires serialization:

var condensed = JsonSerializer.Serialize(schema);
var indented = JsonSerializer.Serialize(schema, new JsonSerializerOptions { WriteIndented = true };

Typically you want .ToString() to remain fairly simple and quick.


In regard to adding references with the fluent syntax, the best way is to just call the .Ref() extension method with a string reference:

var internalRefSchema = new JsonSchemaBuilder()
    .Defs(("myObj", new JsonSchemaBuilder().Type(SchemaValueType.Object)))
    .Ref("#/$defs/myObj")
    .Build();
var externalRefSchema = new JsonSchemaBuilder()
    .Ref("https://myserver.org/schema/myschema.json")
    .Build();

I haven't figured out a way to do a definition and a reference in such a way that it's compile-time checked. You're just going to need to be sure that your strings are right.

For more fluent usage example, you can look at the code for the meta-schemas.

@martinp999
Copy link
Author

Many thanks for that. Both of your suggestions worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants