{"id":36353739,"url":"https://github.com/kingwill101/schema2dart","last_synced_at":"2026-01-13T22:01:10.917Z","repository":{"id":331864890,"uuid":"1127618374","full_name":"kingwill101/schema2dart","owner":"kingwill101","description":"Generate strongly typed dart models from  json schema ","archived":false,"fork":false,"pushed_at":"2026-01-05T11:51:29.000Z","size":500,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-01-11T16:23:39.740Z","etag":null,"topics":["dart","dartlang","json-schema","json-schema-generat","validation"],"latest_commit_sha":null,"homepage":"","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kingwill101.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-01-04T08:57:48.000Z","updated_at":"2026-01-06T04:04:59.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/kingwill101/schema2dart","commit_stats":null,"previous_names":["kingwill101/schema2dart"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/kingwill101/schema2dart","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingwill101%2Fschema2dart","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingwill101%2Fschema2dart/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingwill101%2Fschema2dart/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingwill101%2Fschema2dart/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kingwill101","download_url":"https://codeload.github.com/kingwill101/schema2dart/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kingwill101%2Fschema2dart/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28400397,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-13T14:36:09.778Z","status":"ssl_error","status_checked_at":"2026-01-13T14:35:19.697Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dart","dartlang","json-schema","json-schema-generat","validation"],"created_at":"2026-01-11T13:39:05.124Z","updated_at":"2026-01-13T22:01:10.911Z","avatar_url":"https://github.com/kingwill101.png","language":"Dart","funding_links":["https://www.buymeacoffee.com/kingwill101"],"categories":[],"sub_categories":[],"readme":"# schema2dart\n\n[![Pub Version](https://img.shields.io/pub/v/schema2dart)](https://pub.dev/packages/schema2dart)\n[![License](https://img.shields.io/github/license/kingwill101/schema2dart)](LICENSE)\n[![Buy Me a Coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-FFDD00?logo=buy-me-a-coffee\u0026logoColor=black)](https://www.buymeacoffee.com/kingwill101)\n\n**Production-ready JSON Schema to Dart code generator with full JSON Schema 2020-12 support.**\n\nGenerate strongly-typed, immutable Dart models from JSON schemas with runtime validation, security controls, and excellent developer experience.\n\n## ✨ Features\n\n- 🔧 **Build Runner Integration** - Automatic code generation during development\n- 📦 **Standalone API** - Programmatic generation for CLI tools and custom builds\n- ✅ **Full JSON Schema 2020-12 Compliance** - All core applicators and keywords\n- 🛡️ **Security-First** - Offline-by-default with configurable allowlists\n- 🎯 **Type Safety** - Immutable classes with proper null safety\n- ⚡ **Validation Helpers** - Optional runtime validation with detailed errors\n- 🔗 **Reference Resolution** - `$ref`, `$anchor`, `$dynamicAnchor` support\n- 📝 **Rich Documentation** - Schema descriptions become doc comments\n- 🎨 **Extension Annotations** - Preserve `x-*` custom metadata\n\n## 🚀 Quick Start\n\n### Using build_runner (Recommended)\n\n**1. Add dependency**\n\n```yaml\n# pubspec.yaml\ndev_dependencies:\n  schema2dart: ^latest_version\n  build_runner: ^2.4.0\n```\n\n**2. Configure builder**\n\n```yaml\n# build.yaml\ntargets:\n  $default:\n    builders:\n      schema2dart|schema_builder:\n        options:\n          emit_validation_helpers: true\n        generate_for:\n          - lib/schemas/**/*.json\n```\n\n**3. Add schema**\n\n```json\n// lib/schemas/person.json\n{\n  \"type\": \"object\",\n  \"properties\": {\n    \"name\": {\"type\": \"string\"},\n    \"age\": {\"type\": \"integer\", \"minimum\": 0}\n  },\n  \"required\": [\"name\"]\n}\n```\n\n**4. Generate**\n\n```bash\ndart run build_runner build --delete-conflicting-outputs\n```\n\n**5. Use**\n\n```dart\nimport 'package:your_package/schemas/person.dart';\n\nvoid main() {\n  final person = Person(name: 'Alice', age: 30);\n  print(person.toJson());\n  \n  person.validate(); // Runtime validation\n}\n```\n\n### Using the API\n\n```dart\nimport 'package:schema2dart/schema2dart.dart';\n\nvoid main() {\n  final schema = {\n    'type': 'object',\n    'properties': {\n      'name': {'type': 'string'},\n    },\n  };\n\n  final generator = SchemaGenerator(\n    options: SchemaGeneratorOptions(\n      rootClassName: 'Person',\n      emitValidationHelpers: true,\n    ),\n  );\n\n  final code = generator.generate(schema);\n  print(code); // Generated Dart code\n}\n```\n\n## 🌟 Advanced Features\n\n### Helper Functions\n\nGenerate convenient top-level parse/stringify functions (programmatic API):\n\n```dart\nfinal generator = SchemaGenerator(\n  options: const SchemaGeneratorOptions(\n    generateHelpers: true,\n  ),\n);\n```\n\n```dart\n// Generated code includes:\nPerson personFromJson(String str) =\u003e Person.fromJson(json.decode(str));\nString personToJson(Person data) =\u003e json.encode(data.toJson());\n\n// Usage:\nfinal person = personFromJson('{\"name\": \"Alice\", \"age\": 30}');\nprint(personToJson(person));\n```\n\n### Sealed Class Unions (oneOf/anyOf)\n\nType-safe union types with exhaustive pattern matching:\n\n```json\n{\n  \"oneOf\": [\n    {\"type\": \"string\"},\n    {\"type\": \"integer\"},\n    {\"type\": \"object\", \"properties\": {\"id\": {\"type\": \"string\"}}}\n  ]\n}\n```\n\n```dart\n// Generated sealed class hierarchy:\nsealed class Value {}\nclass ValueString extends Value { final String value; }\nclass ValueInteger extends Value { final int value; }\nclass ValueObject extends Value { final String id; }\n\n// Type-safe pattern matching:\nString describe(Value v) =\u003e switch (v) {\n  ValueString(value: final s) =\u003e 'String: $s',\n  ValueInteger(value: final i) =\u003e 'Int: $i',\n  ValueObject(id: final id) =\u003e 'Object: $id',\n};\n```\n\n### Reserved Keyword Handling\n\nAutomatically handles Dart reserved words:\n\n```json\n{\n  \"properties\": {\n    \"class\": {\"type\": \"string\"},\n    \"const\": {\"type\": \"integer\"}\n  }\n}\n```\n\n```dart\n// Generated with safe field names and explicit mapping in toJson/fromJson:\nclass MyClass {\n  final String class$;\n  final int? const$;\n\n  const MyClass({\n    required this.class$,\n    this.const$,\n  });\n\n  factory MyClass.fromJson(Map\u003cString, dynamic\u003e json) {\n    final class$ = json['class'] as String;\n    final const$ = json['const'] as int?;\n    return MyClass(class$: class$, const$: const$);\n  }\n\n  Map\u003cString, dynamic\u003e toJson() =\u003e {\n    'class': class$,\n    if (const$ != null) 'const': const$,\n  };\n}\n```\n\n### Usage Documentation\n\nUsage docs are available via the programmatic API (not exposed in the build\nrunner options yet):\n\n```dart\nfinal generator = SchemaGenerator(\n  options: const SchemaGeneratorOptions(\n    emitUsageDocs: true,\n    emitReadmeSnippets: true,\n  ),\n);\n```\n\n## ⚙️ Configuration Options\n\n### Build Runner Options\n\nBuild runner currently supports a focused set of options:\n\n| Option | Type | Default | Description |\n| --- | --- | --- | --- |\n| `root_class` | String | derived | Override the root class name |\n| `prefer_camel_case` | bool | `true` | Convert property names to camelCase |\n| `emit_docs` | bool | `true` | Emit doc comments from schema metadata |\n| `header` | String | _none_ | Custom file header |\n| `single_file_output` | bool | `false` | Emit a single `.dart` file vs split parts |\n| `emit_validation_helpers` | bool | `true` | Generate `validate()` methods |\n| `enable_format_hints` | bool | `false` | Map known `format` values to richer Dart types |\n| `enable_format_assertions` | bool | `false` | Enforce `format` validation for registry formats |\n| `enable_content_keywords` | bool | `false` | Enable `contentEncoding`/`contentMediaType` typing |\n| `enable_content_validation` | bool | `false` | Validate decoded content against `contentSchema` |\n| `emit_usage_docs` | bool | `false` | Emit usage docs in generated output |\n| `generate_helpers` | bool | `false` | Emit top-level JSON helper functions |\n| `emit_readme_snippets` | bool | `false` | Emit README snippets in multi-file plans |\n| `allow_network_refs` | bool | `false` | Permit network `$ref` resolution |\n| `network_cache_path` | String | `.dart_tool/schema2dart/cache` | Cache directory for fetched refs |\n| `default_dialect` | String | `latest` | Dialect URI or `none` to require explicit `$schema` |\n| `include_globs` | String or List\u003cString\u003e | `**/*.schema.json`, `**/*.json` | File globs to include |\n\nExample `build.yaml`:\n\n```yaml\ntargets:\n  $default:\n    builders:\n      schema2dart|schema_builder:\n        options:\n          emit_validation_helpers: true\n          default_dialect: \"latest\"\n          include_globs:\n            - lib/schemas/**/*.json\n        generate_for:\n          - lib/schemas/**/*.json\n```\n\n`include_globs` is an additional filter applied inside the builder; `generate_for`\nstill controls what build_runner feeds into the builder.\n\nFor advanced options (format hints, usage docs, custom loaders, security\nallowlists), use the programmatic API below.\n\n### Programmatic API Options\n\n```dart\nSchemaGeneratorOptions(\n  // Code generation\n  rootClassName: 'MyClass',\n  preferCamelCase: true,\n  emitDocumentation: true,\n  singleFileOutput: false,\n  generateHelpers: true,\n  emitUsageDocs: true,\n  emitReadmeSnippets: true,\n\n  // Validation \u0026 types\n  emitValidationHelpers: true,\n  enableFormatHints: true,\n  enableFormatAssertions: false,\n  enableContentKeywords: false,\n  enableContentValidation: false,\n\n  // Security (see REFERENCE_GOVERNANCE.md)\n  allowNetworkRefs: false,\n  allowedNetworkHosts: ['schemas.company.com'],\n  allowedFilePaths: ['/workspace/schemas'],\n  maxReferenceDepth: 50,\n  networkCachePath: '.dart_tool/schema2dart/cache',\n  defaultDialect: SchemaDialect.latest,\n  supportedDialects: SchemaDialect.defaultDialectRegistry,\n\n  // Custom resolution\n  documentLoader: customLoader,\n  onWarning: (msg) =\u003e print(msg),\n)\n```\n\n## 📋 Supported JSON Schema Features\n\n### Core Types ✅\n- Objects, arrays, strings, numbers, integers, booleans\n- Nullable types and optional properties\n- Enums with type-safe extensions\n- **Mixed-type enums** - Sealed classes for heterogeneous enum values\n- Const values\n\n### Validation ✅\n- String: `minLength`, `maxLength`, `pattern`, `format` (assertions opt-in)\n- Number: `minimum`, `maximum`, `multipleOf`\n- Array: `minItems`, `maxItems`, `uniqueItems`, `contains`, `minContains`, `maxContains`\n- Object: `required`, `minProperties`, `maxProperties`, `propertyNames`\n\n### Composition ✅\n- `allOf` - Type intersection\n- `oneOf` - **Discriminated unions with sealed classes**\n- `anyOf` - **Flexible unions with sealed classes**\n- `not` - Type negation\n- **Sealed class unions** - Type-safe union types with exhaustive pattern matching\n\n### Applicators ✅\n- `properties`, `additionalProperties`, `patternProperties`\n- `items`, `prefixItems` (2020-12)\n- `dependentSchemas`, `dependentRequired`\n- `unevaluatedProperties`, `unevaluatedItems` (2020-12)\n- `if`/`then`/`else` conditionals\n\n### References ✅\n- `$ref` - Schema references\n- `$anchor` - Named anchors\n- `$dynamicAnchor`/`$dynamicRef` - Dynamic resolution\n- `$id` - Schema identification\n- Circular reference detection\n\n### Metadata ✅\n- `title`, `description` → Doc comments\n- `deprecated` → `@Deprecated` annotation\n- `default`, `examples` → Preserved\n- `x-*` extensions → Custom annotations\n\n### Dialects ✅\n- JSON Schema Draft 2020-12 (full support)\n- Draft 2019-09, Draft-07, Draft-06, Draft-04\n- Configurable default dialect\n\n### Limitations ⚠️\n- `contentMediaType`, `contentEncoding`, `contentSchema` - Content decoding supported; contentSchema validation limited to JSON media types\n- Format hints require `enableFormatHints: true`\n- Format assertions require `enableFormatAssertions: true`\n- Content validation requires `enableContentValidation: true`\n\nSee [LIMITATIONS.md](LIMITATIONS.md) for details and workarounds.\n\n## 🎯 Examples\n\nCheck out the [`example/`](example/) directory for:\n\n- **[build_runner_example](example/build_runner_example/)** - Full build runner setup\n- **[schema2dart_example.dart](example/schema2dart_example.dart)** - Standalone API example\n- **[helper_functions_example.dart](example/helper_functions_example.dart)** - Top-level helpers\n- **[sealed_unions_example.dart](example/sealed_unions_example.dart)** - `oneOf`/`anyOf` unions\n- **[format_assertions_example.dart](example/format_assertions_example.dart)** - `format` validation\n- **[content_validation_example.dart](example/content_validation_example.dart)** - `contentSchema` validation\n- **[reserved_keywords_example.dart](example/reserved_keywords_example.dart)** - Reserved words\n- **[Real schemas](example/schemas/)** - GitHub workflows, actions, and more\n\n## 🔒 Security\n\nschema2dart is **secure by default**:\n\n- ✅ **Offline-by-default** - No network access without explicit opt-in\n- ✅ **Allowlists** - Fine-grained control over hosts and file paths\n- ✅ **Cycle detection** - Prevents infinite recursion\n- ✅ **Depth limits** - Configurable maximum reference depth\n- ✅ **Clear errors** - Actionable security messages\n\nSee [REFERENCE_GOVERNANCE.md](REFERENCE_GOVERNANCE.md) for full details.\n\n## 🆚 Comparison\n\n| Feature | schema2dart | quicktype | json_serializable |\n|---------|-------------|-----------|-------------------|\n| JSON Schema 2020-12 | ✅ Full | ⚠️ Partial | ❌ No |\n| Build runner | ✅ | ❌ | ✅ |\n| Standalone API | ✅ | ✅ | ❌ |\n| Runtime validation | ✅ | ❌ | ❌ |\n| Security controls | ✅ | ❌ | N/A |\n| Circular refs | ✅ | ✅ | ⚠️ |\n| oneOf/anyOf | ✅ | ✅ | ❌ |\n| Documentation | ✅ Excellent | ⚠️ Basic | ✅ Good |\n\n## 🛠️ Development\n\n### Setup\n\n```bash\ngit clone https://github.com/kingwill101/schema2dart.git\ncd schema2dart\ndart pub get\n```\n\n### Running Tests\n\n```bash\ndart test\n```\n\n### Code Quality\n\n```bash\ndart analyze\ndart format .\n```\n\n### Building Examples\n\n```bash\ncd example/build_runner_example\ndart pub get\ndart run build_runner build --delete-conflicting-outputs\ndart run\n```\n\n## 🤝 Contributing\n\nContributions are welcome!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkingwill101%2Fschema2dart","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkingwill101%2Fschema2dart","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkingwill101%2Fschema2dart/lists"}