Choose sample-based inference for a reviewable starting point, and use an authoritative API contract to finalize types when nullability, numeric ranges, or variant behavior matter. JSON-to-Rust conversion is not one mechanical mapping: a payload sample proves what appeared, while a production contract must define what is allowed.
For exploratory work or an undocumented payload, the JSON to Rust Struct Converter can turn one strict JSON sample into Rust source with Serde derives. It emits local source text without uploading the sample, but it does not compile Rust, install crates, or execute the generated code. That makes it useful for producing a draft to inspect, not for replacing contract review and tests in the destination project.

Match the conversion method to your evidence
The best approach depends on whether the JSON shape is merely observed or formally specified. Choose the narrowest approach that reflects the strongest evidence available.
| Approach | Choose it when | What to review |
|---|---|---|
| Contract-first Serde type | API documentation or a schema defines fields, requiredness, numeric ranges, and variants. | Domain-specific types, validation rules, and whether missing and null values have different meanings. |
| Sample-inferred Serde draft | A representative strict JSON sample is available and the shape is still being explored. | Every inferred scalar type, Option, nested struct, rename, and mixed-value fallback. |
| Flexible value at the boundary | Records legitimately contain different shapes or the accepted variants are not yet known. | How unknown values are validated and converted into typed domain data later. |
Sample inference is useful when speed matters, provided the result remains a draft. The referenced converter accepts one JSON sample rather than an API schema, so its output cannot establish required fields, closed variant sets, or future behavior. If documentation exists, use it to promote or replace the inferred types. If no contract exists, preserve uncertainty with serde_json::Value where coercing different shapes into one Rust type would be misleading.
Translate JSON evidence into explicit Rust decisions
Review the mapping rather than accepting it mechanically. The converter follows these rules:
| JSON evidence | Generated Rust representation | Decision to review |
|---|---|---|
| String | Owned String | Replace it if the domain value is a UUID, date, URL, enum, borrowed slice, or secret. |
| Boolean | bool | Confirm that the field is truly a two-state value rather than a variant encoded as a string. |
| Safe JSON integer | i64 | Check whether the contract instead requires u64, i128, a decimal type, or a string. |
| Other JSON number | f64 | Check precision, range, and whether decimal semantics must be preserved. |
| Array | Vec of the merged element type | Review element consistency and the special case of an empty array. |
| Null without another observed type | Option<serde_json::Value> | Identify the intended type when more evidence becomes available. |
| Null combined with an observed type | Option of that type | Confirm that null is valid for the field. |
| Object | A public struct with Serialize, Deserialize, and Debug derives | Review nested names, field requiredness, and wire-name preservation. |
| Incompatible mixed values | serde_json::Value | Decide whether the domain needs an explicit enum, a tagged enum, or flexible handling. |
Arrays are merged into a common element type. When an array contains objects, fields observed in every object remain required, while a field missing from at least one object becomes Option. An empty array becomes Vec<serde_json::Value> because the sample contains no evidence for an element type. Integer and decimal observations merge to f64 rather than silently retaining two incompatible numeric assumptions.
JSON keys are normalized to ASCII snake_case Rust fields. Camel-case boundaries, spaces, punctuation, and hyphens become underscores. Leading digits are prefixed, Rust keywords receive a trailing underscore, and normalized collisions receive numeric suffixes. A serde rename attribute preserves the original wire name whenever the Rust field differs from the JSON key. These transformations keep identifiers usable under Rust's identifier rules, but the generated names and renames still deserve a direct comparison with the wire format.
Nested objects become named nested structs, with names derived safely from their path. Review those names for clarity and collisions. If a future response can contain fields that are absent from the current sample, do not treat the current struct as proof that those fields are optional.
Resolve numbers, nulls, and mixed values deliberately
An Option in the generated source can have more than one cause. It may represent a JSON null, or it may reflect a key missing from at least one object in an array. Neither observation proves the complete API contract. Consult the field's documentation to decide whether it is required, nullable, or conditionally present. A required field should not remain optional merely because the sample did not demonstrate its presence.
Incompatible mixed values fall back to serde_json::Value rather than causing the converter to invent an enum or choose the first type. That behavior preserves uncertainty, which is useful while investigating a payload. If documentation identifies a closed set of variants, define an explicit Rust enum by hand and add the required serialization behavior. The generator does not infer tagged-enum design.
Safe JSON integers map to i64, while other JSON numbers map to f64. JSON numbers are parsed by JavaScript before inference, so an unsafe integer spelling cannot be represented exactly and falls away from i64 inference. Keep precision-sensitive identifiers and decimals as strings in the source contract when exact representation matters. Likewise, do not let f64 stand in for a value that the domain defines as u64, i128, or a decimal type without an explicit decision.
Generate, compile, and round-trip the candidate
- Paste representative strict JSON and choose the root name. Enter an ASCII root type name. The sample may be an object, array, or primitive. Keep precision-sensitive values as strings when the original numeric representation must survive unchanged.
- Generate the source and inspect every inference. Review numeric widths, Options, mixed values, nested type names, serde renames, keyword suffixes, and collision suffixes. Confirm that required fields and wire names match the known contract.
- Copy the source into a Serde-enabled Rust project. The destination's Cargo.toml must pin compatible versions with serde derive support and will normally need serde_json for JSON parsing. The converter introduces neither dependency and does not add crate paths.
- Format, compile, and round-trip real fixtures. Run cargo fmt and cargo check in the project, then parse representative JSON with serde_json into the new type and serialize it back. Test both expected-success and known-failure fixtures rather than relying on the original sample alone.
The generated derives rely on the Serde framework. Compilation is an important separate stage: it exposes missing dependencies, incorrect paths, type mismatches, and other issues that source generation cannot establish. During round-trip testing, check both the values that should survive and the application rules that should reject malformed or incomplete records.
Separate inference from contract decisions
Some domain information cannot be recovered from a JSON shape. A string may represent a UUID, date, URL, enum, borrowed slice, or secret. A small integer may need u64, i128, Decimal, or string semantics. Mixed objects may deserve a tagged enum rather than a flexible field. A field present in the sample may be optional elsewhere, so these cases require human decisions based on authoritative documentation.
The generator also does not add module visibility policy, lifetimes, generics, custom serializers, deny_unknown_fields, defaults, flattening, tagging, or validation. That is a limitation, not a reason to discard the draft. Add only the behavior your application requires, and keep those additions visible in code review.
Validate against documentation and fixtures
Use authoritative API documentation and several success and failure fixtures as the final reference. Include cases for null versus absence, numeric boundaries, precision-sensitive strings, documented enum variants, omitted fields, and unexpected shapes. Confirm that serde rename attributes preserve the exact wire keys and that the chosen handling for unknown or mixed data matches the application requirement.
A successful round trip shows that the sample can move through the chosen Rust type. It does not prove that the type models every valid response. If the API evolves, revisit optionality, variants, and numeric choices instead of assuming the first generated struct remains authoritative.
Know the converter's boundaries
The input must be strict JSON. Comments, trailing commas, NaN, Infinity, BigInt syntax, undefined, and JavaScript object literals are rejected. Work is bounded at 500,000 input characters, 50,000 values, 40 nesting levels, and 1,000,000 output characters. Larger or deeper inputs may not complete.
The page emits source text only. It does not compile Rust, install crates, execute generated code, or upload the sample. Treat its output as an inference candidate, review it against the contract, and validate it through the destination project's formatter, compiler, and round-trip tests.
If you're weighing options, JSON to XML Bulk Conversion: A Practical Workflow covers this in detail.
If you're weighing options, How to Avoid Mistakes When Converting JSON to Zod Schema covers this in detail.