logo
GeekFormat

JSON to PHP

Free online JSON to PHP tool, convert JSON to runnable PHP classes in one click. Supports ArrayObject and stdClass styles, auto-generates namespace, typed properties (PHP 7.4+), optional readonly class (PHP 8.1+), implements JsonSerializable, nested objects automatically split into independent classes, arrays automatically converted to PHP array, runs locally in browser, no upload required.

Related

About JSON to PHP class and PHP entity modeling

JSON to PHP tool (JSON to PHP Converter) is a utility that automatically converts JSON data structures to standard PHP class code. It frees developers from repetitive work of writing namespace / class / public properties / constructors manually, especially suitable for quickly converting sample JSON in API interface docs to PHP entity classes directly require-able into Composer projects.

This tool supports 4 mainstream code styles: ① ArrayObject style (extends \ArrayObject, supports array access and object access, commonly used in Laravel / Symfony Serializer ecosystems); ② stdClass style (extends \stdClass, only object access, WordPress / json_decode default behavior); ③ readonly class style (PHP 8.1+ final readonly class, immutable after construction, suitable for DTO); ④ Laravel integration style (implements Jsonable + Arrayable, works with Eloquent API Resource). Developers can freely choose according to framework used by project.

PHP type mapping is core of JSON to PHP. Tool maps JSON basic types to PHP standard types: strings map to string, integers to int, floats to float, booleans to bool, arrays to array, nested objects to independent classes (capitalized field names), null to ?type (nullable property). All properties declared with PHP 7.4+ typed properties; IDE can directly do type checking.

Another differentiating highlight is 'auto-implement JsonSerializable interface': each generated PHP class automatically implements \JsonSerializable and generates public function jsonSerialize(): mixed { return [...] } method. This means you can directly echo json_encode($user) to output JSON string; json_encode automatically calls array data returned by jsonSerialize(). With Jsonable interface in Laravel you can directly return response()->json($user) without any extra processing.

Unlike some online tools that require uploading JSON to server for processing, all calculations of this tool complete in-browser. quicktype-core loads and executes via Web Worker; JSON parsing, type inference, PHP code generation, ZIP packaging all happen locally, no data sent to any server. This is especially important for JSON containing API keys, user privacy fields or unreleased business structures; data clears from memory after page close.

Generated code usually needs to be placed in Composer project for use. You need to ensure PHP version meets requirements in composer.json (PHP 7.4+ supports typed properties, PHP 8.1+ supports readonly class), then copy generated classes to src directory, autoload via namespace (PSR-4). Afterwards you can consume data with json_decode($jsonString, false) or json_decode($jsonString, true) + deserialization, enjoying convenience of PHP type system.

Use Cases

  • Laravel backend development: quickly convert API doc sample JSON to Eloquent Model / API Resource classes, directly serialize responses with Laravel built-in Jsonable / Arrayable interfaces
  • Symfony Serializer integration: convert third-party API returned JSON to ArrayObject style PHP classes, deep object mapping and data validation with Symfony Serializer
  • WordPress REST API: convert custom endpoint returned JSON structure to stdClass style PHP classes, direct output with wp_send_json(), matching wp_json_encode() default behavior
  • PHP 8.1+ readonly DTO: convert JSON to final readonly class for Data Transfer Objects (DTO), immutable after construction, preventing business logic from accidentally modifying response data
  • Composer package development: convert JSON Schema to PHP classes then publish to Packagist as SDK model layer, reused by other Composer projects via require
  • Unit test fixture: convert JSON fixture to PHP classes then use json_decode + deserialization for test data driving, assert structured fields
  • Data migration scripts: convert JSON configuration files to PHP classes for strongly-typed business logic access, better IDE autocomplete and type checking than array access
  • Frontend Mock integration: backend first converts JSON models to PHP classes; frontend simultaneously gets corresponding TypeScript interface / PHP class, keeping types consistent across both ends
  • Code review: convert API returned JSON directly to readable PHP classes, facilitating discussion of field naming, property visibility during Code Review
  • Legacy project refactoring: refactor code dynamically accessed via associative arrays to strongly-typed PHP class access, static analysis with PHPStan / Psalm
  • PHPUnit DataProvider: convert JSON test data to PHP classes then inject test cases via DataProvider, IDE auto-suggests property fields
  • snake_case backend API integration: backend API returns snake_case fields; frontend PHP system enables 'convert to camelCase' + ArrayObject style for seamless integration
  • PHPStan static analysis: generated classes naturally come with type declarations; intercept type errors in CI with phpstan analyse --level=8
  • Teaching and training: convert sample JSON to PHP classes in PHP teaching scenarios to demonstrate OOP modeling, type system, interface implementation
  • API Gateway layer: convert JSON returned by upstream microservices to PHP classes for gateway layer aggregation; downstream PHP services consume via class properties strongly-typed
  • Message queue consumption: convert JSON message bodies consumed from RabbitMQ / Kafka to PHP classes then store or forward; strict parsing with JSON_THROW_ON_ERROR
  • E-commerce SKU / SPU modeling: convert product JSON structures (multi-spec / multi-image / multi-attribute) to PHP classes, with ArrayObject style for N+1 query optimization in Laravel
  • WebHook callback signature verification: convert JSON signature verification structures from payment gateways, logistics callbacks to PHP classes, signature verification with hash_hmac()
  • OpenAPI toolchain: convert OpenAPI 3.x schema JSON to PHP classes, integrate with Swagger Codegen / Apifox PHP client generation flow
  • Data ETL pipeline: convert JSON from upstream data sources (MySQL JSON fields / MongoDB / Elasticsearch) to PHP classes then data cleaning and storage

How to Use

  1. Paste JSON object (recommended) or array in left editor, or click 'Sample' to load Chinese sample (with nested address / company / tags)
  2. Click toolbar 'Settings' button; in popup select: ① set root class name (e.g. User) and namespace (e.g. App\Models); ② select code style (ArrayObject / stdClass / readonly class); ③ select code features (typed properties / Laravel integration / Symfony Serializer); ④ select field naming strategy (keep original / camelCase / all lowercase / UPPER_SNAKE)
  3. Tool auto-converts within 400ms; right displays all generated PHP classes (each class one independent card, title bar shows current style badge in real-time); if JSON has format error, 'Repair JSON' button appears
  4. Check generated class names, property names and interfaces match expectations; if adjustment needed, modify source JSON key names or reopen Settings to modify options
  5. When satisfied, click single class 'Copy' button to paste to IDE, or click toolbar 'Download ZIP' to one-click download all classes (directory structure organized by namespace path)

Features

  • Two code styles freely switchable: ArrayObject (extends \ArrayObject, supports $obj['key'] array-style access) / stdClass (extends \stdClass, supports $obj->key object-style access), compatible with Laravel serialization, WordPress REST, Symfony Serializer and other scenarios
  • Complete PHP template: auto-generate namespace declaration + use statements + class header comment (Copyright + generation timestamp) + class definition + typed public properties (PHP 7.4+), can be directly required into Composer project without manual boilerplate
  • JsonSerializable interface auto-implemented: each class auto-generates public function jsonSerialize(): mixed { return [...] }, directly serializes JSON with json_encode(), zero extra boilerplate
  • PHP 8.1+ readonly class optional: when enabled, generated class adds final readonly class, all properties readonly, immutable after construction, suitable for immutable API response DTO scenarios
  • Smart type inference: string → string, integer → int, float → float, bool → bool, array → array, nested objects → independent class, null → ?type (nullable property), no manual field type specification needed
  • Nested classes auto-split: nested objects generate independent PHP classes with capitalized field names (e.g. address → Address), objects in arrays named by 'remove trailing s' rule (e.g. users → User), all nested classes also implement JsonSerializable
  • 4 field naming strategies: keep original / snake_case to camelCase (user_name → userName) / all lowercase / UPPER_SNAKE constant style, matching PSR-1 / Laravel / Symfony code conventions
  • Laravel one-click integration: when checked, auto-implements Jsonable, Arrayable interfaces, adds toArray() / toJson() methods, can be directly used as Eloquent API Resource with Composer autoload
  • Copy single class + ZIP multi-file download: each PHP class has independent 'Copy' button, one-click download of ZIP package organized by namespace directory structure (e.g. App/Models/User.php), unzip and use
  • Local browser run + history: JSON parsing, PHP class generation, ZIP packaging all complete in browser via JavaScript (quicktype-core + JSZip), data not uploaded to any server; built-in localStorage history for recent 200 inputs

Code Examples

PHP: Serialize classes generated by this tool with json_encode()

php

PHP classes generated by this tool implement JsonSerializable interface by default, directly output JSON with json_encode() without any extra processing.

<?php

require_once 'vendor/autoload.php';

use App\Models\User;

// Simulate JSON string received from API
$jsonString = '{"id":1,"name":"Alice","email":"alice@example.com","isActive":true}';

// 1) Deserialize to class generated by this tool
$userData = json_decode($jsonString, true);
$user = new User(
    $userData['id'],
    $userData['name'],
    $userData['email'],
    $userData['isActive']
);

// 2) Strongly-typed field access (IDE autocomplete + PHPStan static check)
echo $user->name;          // Alice
echo $user->email;         // a****@***********example.com
echo $user->isActive ? 'Active' : 'Disabled'; // Active

// 3) json_encode() automatically calls jsonSerialize(), no extra code needed
echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
/*
{
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com",
    "isActive": true
}
*/

PHP: Laravel API Resource integration example

php

After checking Laravel integration, classes generated by this tool can be directly used as Eloquent API Resource, formatting responses with toArray() / toJson().

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * GET /api/users/{id}
     */
    public function show(int $id): JsonResponse
    {
        // 1) Get data from database or external API
        $userData = $this->fetchUserFromApi($id);

        // 2) Wrap with User class generated by this tool
        $user = new User(
            $userData['id'],
            $userData['name'],
            $userData['email'],
            $userData['isActive']
        );

        // 3) Directly return response()->json($user)
        //    Laravel automatically calls jsonSerialize()
        return response()->json($user);
    }

    /**
     * POST /api/users
     */
    public function store(Request $request): JsonResponse
    {
        // 4) Reverse usage: deserialize request JSON to User class
        $user = User::fromArray($request->all());

        // 5) Get array form with toArray()
        $payload = $user->toArray();

        // 6) Execute business logic (e.g. storage / call third-party API)
        $this->userService->create($payload);

        return response()->json([
            'message' => 'User created',
            'data' => $user,
        ], 201);
    }
}

/*
 * Corresponding composer.json dependencies:
 * "require": {
 *     "php": "^8.1",
 *     "laravel/framework": "^11.0"
 * }
 */

PHP: Symfony Serializer integration example

php

Classes generated in ArrayObject style by this tool can work with Symfony Serializer component for deep serialization and deserialization, suitable for complex API gateway layers.

<?php

namespace App\Service;

use App\Models\User;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;

class UserSerializer
{
    private SerializerInterface $serializer;

    public function __construct(SerializerInterface $serializer)
    {
        // Use PropertyNormalizer to handle public properties
        $this->serializer = $serializer;
    }

    /**
     * Serialize User object to JSON string
     */
    public function toJson(User $user): string
    {
        return $this->serializer->serialize($user, 'json');
    }

    /**
     * Deserialize JSON string to User object
     */
    public function fromJson(string $json): User
    {
        return $this->serializer->deserialize($json, User::class, 'json');
    }

    /**
     * Batch deserialization (e.g. JSON arrays exported from MongoDB)
     */
    public function fromJsonArray(string $jsonArray): array
    {
        $users = [];
        $data = json_decode($jsonArray, true);

        foreach ($data as $item) {
            $users[] = User::fromArray($item);
        }

        return $users;
    }
}

// Usage example
$serializer = new UserSerializer($serializerService);

$json = '{"id":1,"name":"Alice","address":{"city":"Beijing","zip":"100000"},"tags":["php","symfony"]}';

// Deserialize to User object generated by this tool
$user = $serializer->fromJson($json);
echo $user->name;                  // Alice
echo $user->address->city;         // Beijing (strongly-typed access)
print_r($user->tags);              // ['php', 'symfony']

// Serialize back to JSON
$jsonOutput = $serializer->toJson($user);

Best Practices

For most PHP backend projects, ArrayObject style generated classes support both array access ($obj['key']) and object access ($obj->key); plus default implemented JsonSerializable interface, json_encode() automatically calls array returned by jsonSerialize(). This is most universal object data carrier pattern in PHP ecosystem, compatible with almost all mainstream frameworks like Laravel, Symfony, CodeIgniter.

readonly class introduced in PHP 8.1+ is best practice for DTO: properties immutable after construction, preventing business logic from accidentally modifying response data; constructor promotion makes code more concise (public function __construct(public int $id, public string $name) {} one line for property declarations). We recommend changing API response DTOs, WebHook callback structures, third-party API client models to readonly class style.

Laravel database fields default to snake_case, but PHP properties recommend camelCase. 'Convert to camelCase' strategy by this tool auto-converts, while jsonSerialize() return array keys keep original snake_case; json_encode() output still snake_case. This both conforms to Laravel model access habits and maintains API compatibility.

Generated ZIP packages organized by namespace path (e.g. App/Models/User.php). Configure autoload.psr-4 section in composer.json, e.g.: "App\\": "src/", then execute composer dump-autoload. This way Composer automatically maps App\Models\User to src/Models/User.php without manual require.

This tool generates typed properties by default (PHP 7.4+), can have property types fully inferred by PHPStan in --level=8 mode. We recommend integrating phpstan analyse ./src --level=8 in CI pipeline to intercept type errors. Psalm also supports PropertyTypeProvider for strong type validation.

This tool runs completely locally in browser, won't upload any data. But form habits: ① desensitize JSON containing API keys / tokens / user privacy before conversion; ② ensure network disconnected when using this tool for large internal business structures (unreleased interfaces); ③ don't commit sample data with sensitive info to public repositories after generating code.

Nested JSON objects recursively generate independent PHP classes. If JSON nesting levels exceed 6 layers (e.g. multi-level nested menus, org charts, complex business documents), number of generated classes explodes (N nested classes per layer), IDE loads slowly and maintenance difficult. Recommendations: ① split JSON into multiple modules and convert separately; ② or manually refactor to array indexing ($user['profile']['address']['city']) instead of class nesting after generation.

JSON null values are default inferred as ?mixed (nullable mixed), which is safe fallback but not precise type. If field type is known (e.g. "nickname": "" infers string), first give example value in source JSON, after generation remove example value and change to precise type like ?string, significantly improving PHPStan static analysis accuracy.

FAQ

How to convert JSON to PHP class?

Paste JSON content into left input box; tool will auto-convert within 400ms; or click 'Convert' button in toolbar. After conversion, all generated PHP classes display on right; each class has independent 'Copy' button; click 'Download ZIP' in toolbar to package and download all classes (with namespace directory structure).

What JSON data structures are supported?

Two structures supported: ① JSON object (as root class, auto-generates class RootClass); ② JSON array (first object in array as root class template). All nested objects are recursively processed into independent classes; objects in arrays are recursively processed into classes corresponding to array element type.

What content do generated PHP classes contain?

Each generated .php file contains: ① file header comment (Copyright + auto-generated timestamp); ② namespace declaration; ③ use statements (auto-import \JsonSerializable / \ArrayAccess as needed); ④ class definition (ArrayObject / stdClass / readonly class per settings); ⑤ implements interfaces (JsonSerializable / Jsonable / Arrayable per settings); ⑥ typed public properties (PHP 7.4+); ⑦ constructor (full property assignment per settings); ⑧ methods like jsonSerialize() / toArray() / toJson(). Complete and ready for php -l syntax check and require use.

What's the difference between ArrayObject and stdClass styles?

ArrayObject style: generated class extends \ArrayObject, supports both $obj['key'] array access and $obj->key object access, returns object during json_encode(). stdClass style: generated class extends \stdClass, only supports $obj->key object access, lighter but no direct array access. Laravel / WordPress ecosystem uses stdClass style by default (json_decode default behavior), Symfony Serializer uses ArrayObject style by default.

Does it support generating Laravel API Resource?

Yes. After checking 'Laravel one-click integration' option in settings, tool auto-generates implements Jsonable, Arrayable interfaces, adds toJson($options = 0) and toArray() methods; generated classes can be directly used in Eloquent API Resource (like new UserResource($user) or $user->toArray()). Also auto-uses Illuminate\Contracts\Support\Jsonable and Illuminate\Contracts\Support\Arrayable.

What does code generated with PHP 8.1 readonly class mode look like?

After enabling readonly class, generated PHP classes are significantly streamlined. For example, class User with readonly enabled is about 12 lines: final readonly class User implements \JsonSerializable { public function __construct(public int $id, public string $name) {} public function jsonSerialize(): array { return [...] } }. All properties declared as readonly via constructor property promotion, immutable after construction. Note: project requires PHP 8.1+, readonly fields can only be assigned via constructor.

How to convert snake_case field names to camelCase?

In Settings popup 'Field Naming Strategy' group, select 'Convert to camelCase' mode; tool automatically converts JSON field names from snake_case to PHP recommended naming style. E.g. user_name → userName, created_at → createdAt, is_active → isActive. Also if JSON comes from Laravel route binding, class properties can be directly accessed via $request->userName without manual intermediate conversion.

How are nested JSON objects handled?

Tool automatically creates independent PHP classes for nested objects. Naming rules: nested object key capitalized as class name (e.g. address → Address), object key in arrays with trailing s removed then capitalized (e.g. users → User). All nested classes also include complete fields, constructor, jsonSerialize() method, namespace consistent with root class, can be imported via use App\Models\Address.

What do array fields auto-convert to?

Yes. Array fields in JSON automatically convert to PHP array properties; element type auto-inferred from first element. E.g. ["a","b","c"] → array (annotated array<string> in comment); [{...},{...}] → array (annotated array<User> in comment, User is new class named from key); empty array [] defaults to array (annotated array<mixed> in comment). PHP 8.0+ with PHPDoc annotations gives type hints in IDE.

How to modify root class name and namespace?

Settings button in upper right of toolbar; click to popup settings dialog, can set: ① root class name (default JsonRootClass); ② namespace (default App\Models). After modification, all generated class names update synchronously; ZIP directory structure also organized by namespace (e.g. App/Models/User.php).

Is download a single .php file or ZIP package?

Download is ZIP package (User.zip), containing all generated PHP classes organized by namespace path. E.g. when namespace is App\Models, file structure inside ZIP: App/Models/User.php, App/Models/Address.php, App/Models/Company.php, etc. Can be directly imported into Composer project src directory via unzip command or IDE.

Can a single class be copied directly to IDE?

Yes. Each generated PHP class displays as independent card; card upper right has 'Copy' button; clicking copies complete class code (including <?php + namespace + use + class + properties + constructor + methods) to clipboard, can be directly pasted into IDEs like PhpStorm / VS Code / Sublime.

How to make generated classes implement JsonSerializable interface?

Enabled by default. All generated PHP classes automatically implements \JsonSerializable and generate public function jsonSerialize(): array { return [...] } method; return array assembled in class property order. You can directly echo json_encode($user) to output JSON string, or return response()->json($user) in Laravel.

Can Symfony Serializer use classes generated by this tool?

Yes. Symfony Serializer reads data in array style by default, well compatible with generated ArrayObject style classes. Works with SerializerInterface's $serializer->serialize($user, 'json') for direct serialization; deserialization via deserialize() requires public properties or getters. This tool generates public properties + constructor assignment style, directly usable with Symfony Serializer's PropertyNormalizer.

What if JSON has format errors?

Tool automatically detects JSON validity; on error displays red error prompt on right with 'Repair JSON' button. Clicking auto-repairs common errors: ① trailing extra commas; ② single quotes replaced with double quotes; ③ unquoted keys completed with quotes; ④ comments removed. After successful repair, can directly convert to generate PHP classes.

Is data uploaded to server? Is it private and secure?

Completely local browser run. All JSON parsing, PHP class generation, ZIP packaging complete in your browser via JavaScript (quicktype-core + JSZip); input JSON data and generated PHP code never upload to any server, nor recorded or cached to cloud. Sensitive JSON containing internal interface fields, unreleased business structures, unpublished API responses can be used safely; data clears on page close.

Will large JSON with 10,000 lines cause lag?

Tool has no explicit line limit, but browser parsing and rendering of oversized JSON slows down. Recommendations: ① split JSON then batch convert; ② focus on one nesting level at a time; ③ for batch generation of 100+ classes, recommend directly using IDE PHP template plugins or writing simple quicktype CLI script.

Do generated PHP classes support PHP versions below 7.4?

Not fully supported. Classes generated by this tool use PHP 7.4+ typed properties by default (e.g. public int $id). If your project is still PHP 7.0~7.3, type declarations will cause compatibility errors. Recommendations: ① upgrade project to PHP 8.1+ (recommended, better performance and type system); ② or batch remove type declarations in IDE after generation (Find & Replace `public int ` → `public `); ③ or use PHP 7.4 compatible mode (PHP 7.4 is this tool's baseline).

Troubleshooting

Shows 'Please enter JSON data' or right side empty

Left input box is empty or contains only whitespace. Ensure valid JSON content is pasted, or click 'Sample' to load Chinese sample, or click 'Upload' to select .json / .txt files.

Shows 'Unexpected token ... in JSON at position N'

JSON format invalid. Common causes: ① trailing extra commas (e.g. {"a":1,}); ② single quotes used instead of double quotes; ③ JS object notation (e.g. {key: value}) instead of JSON (e.g. {"key": "value"}). Click 'Repair JSON' button to auto-fix some errors.

Generated code errors in PHP 7.x project with 'Typed property must not be accessed before initialization'

Classes generated by this tool use PHP 7.4+ typed properties by default (e.g. public int $id). If your project is still PHP 7.0~7.3, type declarations cause compatibility issues. Solutions: ① upgrade project to PHP 8.1+ (recommended, better performance and type system); ② batch remove type declarations in IDE (Find & Replace `public int ` → `public `); ③ uncheck 'PHP 7.4 typed properties' option (only effective for some code styles).

PHP 8.1 readonly class errors with 'Cannot modify readonly property'

Properties generated in readonly class style cannot be modified after construction. If you try $user->name = 'Bob' it will error. Solutions: ① change to ArrayObject or stdClass style (properties modifiable); ② or create new instance via new User(...) instead of modifying.

Cannot find Illuminate\Contracts\Support\Jsonable in Laravel project

Laravel integration style requires laravel/framework dependency. Ensure in composer.json: "require": { "php": "^8.1", "laravel/framework": "^11.0" }. Then execute composer update to install dependencies. If not using Laravel, please choose ArrayObject or stdClass style instead.

Symfony Serializer deserialization failure 'Cannot denormalize object'

Common causes: ① generated class has no public properties or getter methods (Symfony Serializer uses PropertyNormalizer by default); ② class lacks no-arg constructor but has required parameters. Solutions: ① confirm this tool generated public properties; ② manually construct object via fromArray() static method then pass to Serializer.

Nested object class name not as expected (e.g. categories named Categori)

Tool uses 'remove trailing s + capitalize' naming rule for objects in arrays; for irregular plurals like categories this is not friendly. Recommendations: ① change source JSON key to singular (e.g. categories → category); ② or rename class via IDE Rename after generation (modifying all references simultaneously).

Downloaded ZIP directory structure incorrect after extraction

Directories inside ZIP organized by namespace setting (default App/Models/). If incorrect position after extraction: ① modify namespace name (e.g. to App\Dto) and re-download; ② specify extraction directory with unzip -d src/; ③ or directly File → Open entire extracted folder in IDE.

Generated classes not autoloading

Composer project requires PSR-4 autoload mapping configured in composer.json, e.g.: "autoload": { "psr-4": { "App\\": "src/" } }. Then execute composer dump-autoload; Composer will automatically load class files by namespace-to-directory mapping.

Field name changes after snake_case to camelCase conversion

'Convert to camelCase' changes PHP property names (e.g. user_name → userName), but return array keys in jsonSerialize() method remain original snake_case; json_encode() output JSON still has original field names. So access PHP property as $user->userName, output JSON is still {"user_name": "..."}. If deserialization also wants camelCase access, need to change to camelCase keys in jsonSerialize() return array.

Page lags when generating 100+ nested classes

Tool has no explicit class count limit, but browser rendering performance degrades significantly for oversized DOM. Recommendations: ① split JSON into several independent modules and convert separately; ② or directly use IDE built-in code generation tools (e.g. PhpStorm's JSON to PHP plugin); ③ nesting levels recommended not to exceed 6 layers, otherwise suggest refactoring JSON structure.

Array is numeric type but generates array<int> while actually array<float>

Tool infers type by first element of array (e.g. [1, 2, 3] infers int, [1.5, 2.5] infers float). If you mix integers and floats (e.g. [1, 2.5]), tool infers by first element. Solutions: ① add at least one example float element in source JSON (e.g. [0.0, 1.5]); ② or manually adjust type in PHPDoc annotation after generation.

null value field generated as ?mixed type instead of ?string

JSON null values are by default inferred as ?mixed type by tool (because actual type cannot be determined). This is safe practice avoiding misjudgment. If type is known, give this field an example value in source JSON (e.g. "field": "" infers string), after generation change type to ?string.

Classes still not autoloading after composer dump-autoload

Possible causes: ① namespace doesn't match directory (e.g. namespace App\Models but file in src/Dto/); ② composer.json psr-4 mapping wrong (e.g. "App\\": "src/Dto/" should be "App\\Dto\\": "src/Dto/"). Solutions: check namespace of each .php file strictly corresponds to directory path (namespace segments must equal directory segments, case-sensitive).

PHPStan prompts 'Property does not have default value'

Generated typed properties have no default values; PHPStan considers them potentially uninitialized in --level=8 mode. Solutions: ① disable PHPStan strict rules; ② assign empty values in constructor (e.g. $this->tags = []); ③ use readonly class style (assigned after constructor promotion).

Symfony Serializer object array deserialization failure

For object arrays like [{...},{...}], PropertyNormalizer needs element type hints. Solutions: ① explicitly specify array<User> type in PHPDoc; ② or wrap with ArrayCollection ($users = new ArrayCollection()).

Chinese keys generate PHP property names with special characters

When source JSON contains Chinese keys (e.g. "姓名": "Alice"), tool generates public string $姓名 property; IDE may prompt naming non-standard but won't error. Recommendations: ① change JSON keys to English (more conforming to PHP PSR-1 naming); ② when keeping Chinese, ensure PHP file encoding is UTF-8 (PHP defaults to UTF-8).

ArrayObject style $obj['key'] vs $obj->key output order inconsistency

ArrayObject style array access returns in property declaration order; object access returns in return array order in jsonSerialize() method. If two orders inconsistent, causes echo json_encode() output inconsistent with var_dump($obj). Recommendations: keep jsonSerialize() return order consistent with constructor parameter order.

Numeric ID in WebHook callback JSON exceeds PHP_INT_MAX

PHP's int is 64-bit signed integer on 64-bit systems (max 9223372036854775807); if numeric ID in JSON exceeds this range (e.g. Twitter snowflake IDs), it gets truncated. Solutions: ① receive ID as string type ("id": "1234567890123456789"); ② parse with JSON_BIGINT_AS_STRING flag.

Glossary

namespace
Namespace mechanism introduced in PHP 5.3+ to avoid class name conflicts. This tool auto-generates according to user-set namespace and organizes in ZIP by App/Models/ directory.
class
Template defining objects in PHP. This tool generates standard PHP classes, directly instantiable via new User(...).
ArrayObject
Class in PHP SPL standard library implementing interfaces like ArrayAccess. Classes generated in ArrayObject style by this tool inherit from \ArrayObject, supporting both array-style and object-style dual access.
stdClass
PHP built-in generic object class; json_decode($json, false) returns this type by default. Classes generated in stdClass style by this tool inherit from \stdClass, only supporting object-style access.
typed properties
Property type declarations introduced in PHP 7.4+ (e.g. public int $id). Properties generated by this tool have type declarations by default; IDE and static analysis tools can directly do type checking.
readonly class
Readonly class introduced in PHP 8.1+; all properties in class automatically readonly, cannot be modified after construction. This tool generates final readonly class in readonly style, suitable for DTO immutable scenarios.
JsonSerializable
Interface introduced in PHP 5.4+; objects implementing this interface automatically call jsonSerialize() method when json_encode() is called. All classes by this tool automatically implement this interface.
Jsonable (Laravel)
Contract interface of Laravel framework; after implementation, object can call toJson() to output JSON. Laravel integration style by this tool automatically implements this interface.
Arrayable (Laravel)
Contract interface of Laravel framework; after implementation, object can call toArray() to output array. Laravel integration style by this tool automatically implements this interface.
Composer
PHP official dependency management tool. When using code generated by this tool, need to configure PSR-4 autoload in composer.json (e.g. App\\: src/).
PSR-4
Autoload standard specified by PHP-FIG, loading class files via namespace-to-directory mapping. ZIP package generated by this tool is organized by namespace path, conforming to PSR-4 standard.
Symfony Serializer
Serialization framework of Symfony component. Classes generated in ArrayObject style by this tool can work with Symfony Serializer's PropertyNormalizer for deep serialization and deserialization.
Eloquent API Resource
Laravel Eloquent API resource class for formatting API responses. Classes generated in Laravel integration style by this tool can be directly used as API Resource base classes.
composer.json
Configuration file of Composer project. After placing code generated by this tool into src directory, need to configure autoload section in composer.json and execute composer dump-autoload.
json_encode / json_decode
PHP built-in JSON serialization and deserialization functions. After classes generated by this tool implement JsonSerializable, json_encode() automatically calls jsonSerialize() method.
PHPUnit DataProvider
Data provider mechanism of PHPUnit testing framework. PHP classes generated by this tool can be injected into test cases as DataProvider, improving test writing efficiency with IDE autocomplete.
PHPStan
PHP static analysis tool, can do type checking and error detection on code. Classes generated by this tool, due to having typed properties, can have property types fully inferred by PHPStan in --level=8 mode.
Psalm
Another PHP static analysis tool, open-sourced by Vimeo. Classes generated by this tool, with Psalm's PropertyTypeProvider, can do strong type validation.
Doctrine
ORM and DBAL toolset in PHP ecosystem. PHP classes generated by this tool can serve as skeleton for Doctrine Entity, then manually add annotations like #[ORM\Column].
php -l
PHP command line syntax check directive. Classes generated by this tool can first run php -l User.php for syntax validation before requiring into project.
Composer dump-autoload
Command for Composer to regenerate autoload index. After placing classes generated by this tool into src directory, must execute composer dump-autoload to be recognized by PSR-4 autoload.
JSON_THROW_ON_ERROR
json_decode() error handling flag in PHP 7.3+; when enabled, JSON parsing failure throws JsonException exception. Laravel example by this tool uses strict parsing.
Hash (PHP)
PHP built-in hash function, commonly used for WebHook signature verification. WebHook callback classes generated by this tool work with hash_hmac() for signature verification.

JSON Type to PHP Type Mapping Cheat Sheet

Auto-inferred JSON data types by tool and corresponding PHP type reference:

JSON Value ExampleDetection MethodGenerated PHP TypeProperty Default Value
nullvalue === null?mixed / ?typenull
true / falsetypeof value === 'boolean'boolfalse
42typeof value === 'number' && Number.isInteger(value)int0
3.14typeof value === 'number' && !Number.isInteger(value)float0.0
"hello"typeof value === 'string'string''
[...] (empty array)Array.isArray(value) && value.length === 0array (PHPDoc array<mixed>)[]
["a","b"]Array.isArray(value) && typeof value[0] === 'string'array (PHPDoc array<string>)[]
[1,2,3]Array.isArray(value) && typeof value[0] === 'number'array (PHPDoc array<int>)[]
[{...},{...}]Array.isArray(value) && typeof value[0] === 'object'array (PHPDoc array<Xxx>)[]
{...} (nested object)typeof value === 'object' && !Array.isArray(value)Xxx (independent class)new Xxx()

PHP 4 Code Styles Comparison Table

4 PHP class code styles supported by tool; choose according to project needs:

Code StyleExtends / ModifierImplements InterfaceUse Cases
ArrayObject styleextends \ArrayObjectimplements \JsonSerializableSymfony Serializer ecosystem, need array-style access $obj['key'], PHP stdlib compatibility
stdClass styleextends \stdClassimplements \JsonSerializableWordPress REST API, json_decode default behavior compatibility, lightweight object data carrier
readonly class stylefinal readonly class (no inheritance)implements \JsonSerializablePHP 8.1+, API response DTO, immutable data transfer objects, guaranteed data not modified after construction
Laravel integration styleno inheritance (default)implements \Jsonable, \Arrayable, \JsonSerializableLaravel Eloquent API Resource, Eloquent model layer, controller response formatting

Privacy & Security

All JSON parsing, PHP class generation, ZIP packaging operations of this JSON to PHP tool complete entirely locally in your browser via JavaScript (quicktype-core + JSZip); input JSON data and generated PHP code never upload to any server, nor recorded, cached or stored to cloud. Sensitive JSON containing internal interface fields, unreleased business structures, unpublished API responses can be used safely; all data clears on page close. This tool doesn't use any Cookies for user tracking, doesn't collect email or account info, doesn't embed any third-party analytics scripts; all calculations complete in current device's browser process. Even in offline environment (e.g. disconnected or intranet isolated environment), works normally as long as page resources have been loaded once.

Authoritative References