The import_types! macro is the simplest way to convert JSON Schema documents into Rust types. The generated types are pub and implement Debug, Clone, Serialize, and Deserialize.
Basic Usage
Pass the path to the JSON schema file directly to the macro.
Advanced Configuration
You can customize the generation using several properties:
schema: The path to the JSON schema file.derives: A list of additional derive macros to apply to all generated types.struct_builder: When set to true, generates a builder-style interface for structs.patch: Allows renaming types or adding specific derives to individual types.replace: Replaces a generated type with an existing type from another crate.convert: Overrides how specific JSON Schema constructs (e.g., a string with a specific format) are mapped to Rust types.
// Basic usage
import_types!("../example.json");
// Expanded form with derives
import_types!(
schema = "../example.json",
derives = [schemars::JsonSchema],
);
// Using the struct builder interface
import_types!(
schema = "../example.json",
struct_builder = true,
);
// Example of using a generated builder
let veggie: Veggie = Veggie::builder()
.veggie_name("radish")
.veggie_like(true)
.try_into()
.unwrap();
// Patching types (rename and extra derives)
import_types!(
schema = "../example.json",
patch = {
Veggie = {
rename = "Vegetable",
derives = [ schemars::JsonSchema ],
}
}
);
// Replacing types with existing ones
import_types!(
schema = "../example.json",
replace = {
Ipv6Cidr = my_fancy_networking_crate::Ipv6Cidr,
}
);
// Overriding conversions based on schema constructs
import_types!(
schema = "../example.json",
convert = {
{
type = "string",
format = "uuid",
} = my_fancy_uuid_crate::MyUuid,
}
);