create static method

JsonSchema create(
  1. Object schema, {
  2. SchemaVersion? schemaVersion,
  3. Uri? fetchedFromUri,
  4. RefProvider? refProvider,
  5. List<CustomVocabulary>? customVocabularies,
  6. Map<String, ValidationContext Function(ValidationContext context, String instanceData)> customFormats = const {},
})

Create a schema from JSON data.

This method is synchronous, and doesn't support fetching of remote references, properties, and sub-properties of the schema. If you need remote reference support use createAsync.

The schema can either be a decoded JSON object (Only Map or bool per the spec), or alternatively, a String may be passed in and JSON decoding will be handled automatically.

Implementation

static JsonSchema create(
  Object schema, {
  SchemaVersion? schemaVersion,
  Uri? fetchedFromUri,
  RefProvider? refProvider,
  List<CustomVocabulary>? customVocabularies,
  Map<
          String,
          ValidationContext Function(
              ValidationContext context, String instanceData)>
      customFormats = const {},
}) {
  // Default to assuming the schema is already a decoded, primitive dart object.
  Object? data = schema;

  /// JSON Schemas must be [bool]s or [Map]s, so if we encounter a [String], we're looking at encoded JSON.
  /// https://json-schema.org/latest/json-schema-core.html#rfc.section.4.3.1
  if (schema is String) {
    try {
      data = json.decode(schema);
    } catch (e) {
      throw ArgumentError(
          'String data provided to create is not valid JSON.');
    }
  }

  /// Set the Schema version before doing anything else, since almost everything depends on it.
  schemaVersion = _getSchemaVersion(schemaVersion, data);

  if (data is Map) {
    return JsonSchema._fromRootMap(
      data,
      schemaVersion,
      fetchedFromUri: fetchedFromUri,
      isSync: true,
      refProvider: refProvider,
      customVocabularies: customVocabularies,
      customFormats: customFormats,
    );

    // Boolean schemas are only supported in draft 6 and later.
  } else if (data is bool && schemaVersion >= SchemaVersion.draft6) {
    return JsonSchema._fromRootBool(
      data,
      schemaVersion,
      fetchedFromUri: fetchedFromUri,
      isSync: true,
      refProvider: refProvider,
      customVocabularies: customVocabularies,
      customFormats: customFormats,
    );
  }
  throw ArgumentError(
      'Data provided to JsonSchema.create is not valid: Data must be a Map or a String that parses to a Map (or bool in draft6 or later). | $data');
}