1

I want to create JSON Schema manually using GSON but i dont find any JsonSchema element support in GSON. I dont want to convert a pojo to schema but want to create schema programatically . Is there any way in GSON ? May be something like following.

 **1 JsonSchema schema = new JsonSchema();
 2 schema.Type = JsonSchemaType.Object;
 3 schema.Properties = new Dictionary<string, JsonSchema>
 4{
 5    { "name", new JsonSchema { Type = JsonSchemaType.String } },
 6    {
 7        "hobbies", new JsonSchema
 8        {
 9            Type = JsonSchemaType.Array,
10            Items = new List<JsonSchema> { new JsonSchema { Type = JsonSchemaType.String } }
11        }
12    },
13};**

2 Answers 2

4

You may consider using everit-org/json-schema for programmatically creating JSON Schemas. Although it is not properly documented, its builder classes form a fluent API which lets you do it. Example:

Schema schema = ObjectSchema.builder()
    .addPropertySchema("name", StringSchema.builder().build())
    .addPropertySchema("hobbies", ArraySchema.builder()
        .allItemSchema(StringSchema.builder().build())
        .build())
    .build();

It is slightly different syntax than what you described, but it can be good for the same purpose.

(disclaimer: I'm the author of everit-org/json-schema)

Sign up to request clarification or add additional context in comments.

6 Comments

Hi @erosb how to specify draft dialect and configure definitions ? From your example im unable to configure $schema
When using with programmatic schema construction you don't need to deal with draft versions, you can just call whatever builder method you need (the actual validation won't care about schema version). You also don't need definitions, just store subschemas in fields and local variables and use them in the main schema.
We are trying to programmatically construct a complex polymoprphic runtime dependent schema. We want to share the generated schema upstream through some rest interface are publish as an open-API yml. I think it might be meaningful to add schema dialect.
I get your point that its possible to break-free from definitions by constructing properties as local schema objects...but this is becoming challenging to resolve path for polymorphic schemas involving allOf, anyOf, oneOf.
Hello @erosb, another follow-up question, is it possible to construct the following schema condition - if X property is passed then Y property should be required and non-optional, via if/then clauses ?
|
0

I tried to build a schema as suggested above, see Everit schema builder includes unset properties as null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.