DEV Community

Cover image for JSON to PHP Class Generator: Typed DTOs and API Resources
devTalk
devTalk

Posted on Originally published at dev-talk.com

JSON to PHP Class Generator: Typed DTOs and API Resources

Last updated: 26 November 2026. I could not run the generator itself from my environment, so the classes below are hand-written examples of what a correct result looks like, not tool output. I did run them under PHP 8.3.6 withstrict_typesto test the behavior described. SeeHow this was checked.

An API hands you a JSON payload and you want typed PHP objects instead of nested arrays you poke at with string keys. Writing the classes by hand means counting nested objects, guessing nullability and remembering that first-name is not a legal property name. The JSON to PHP Class Generator on Dev Talk does the first draft in your browser. This article covers what it produces, what to check in the output, and the runtime errors you will hit if the sample JSON was not representative.

What the tool does

You paste a JSON object or a list of records, or load a .json file, and the tool returns typed PHP 8 classes. The page offers two output types: a plain PHP class (a DTO) or a Laravel API Resource. There are fields for the class name and namespace, and these options:

  • PHP version: 8.2+ generates a readonly class, 8.1 uses readonly properties, and 8.0 uses mutable properties.
  • camelCase properties: converts key names to camelCase property names.
  • Add toArray(): adds a method that turns the object back into an array.
  • One file for all classes: puts everything in one file instead of one per class.

Each DTO has a fromArray() method, and toArray() when that option is on. Files are meant to go in folders that match their namespace, such as app/Data or app/Http/Resources. The page says it is free, needs JavaScript, and that your JSON is converted in the browser and never uploaded. I could not verify the privacy claim, so remove real tokens and customer data from a payload before you paste it.

How the tool infers types

Everything comes from the values in your sample, according to the page:

  • Each nested object becomes its own class.
  • Whole numbers become int, and values like 1.5 or 1.0 become float. The page says 1.0 is a float even though it is a whole number.
  • true and false become bool.
  • For a list, every item is merged into one shape. A key that is null or missing in some items becomes nullable with a default of null.
  • A key that holds both numbers and strings gets a union type such as int|string.
  • Keys that are not valid PHP names are converted: first-name becomes $firstName and 2fa becomes $_2fa. fromArray() and toArray() keep the original key names so the JSON round-trips.

The consequence is that the classes are only as good as the sample. If your sample has one item, nothing is optional. If every price in the sample is a whole number, the field may come out as int and break on the first 9.99. Paste a list with several realistic records, including the awkward ones.

What a correct result looks like

The page does not show its example outputs in text, so here is a hand-written pair of classes for an order payload. It is what I would expect from the PHP 8.2+ option with camelCase on and toArray() enabled:

<?php

declare(strict_types=1);

namespace App\Data;

readonly class OrderItem
{
    public function __construct(
        public string $sku,
        public int $qty,
        public float $price,
        public ?string $note = null,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            sku: $data['sku'],
            qty: $data['qty'],
            price: $data['price'],
            note: $data['note'] ?? null,
        );
    }

    public function toArray(): array
    {
        return [
            'sku' => $this->sku,
            'qty' => $this->qty,
            'price' => $this->price,
            'note' => $this->note,
        ];
    }
}

readonly class Order
{
    /** @param OrderItem[] $items */
    public function __construct(
        public int $id,
        public string $firstName,
        public bool $paid,
        public array $items,
        public int|string $reference,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            id: $data['id'],
            firstName: $data['first-name'],
            paid: $data['paid'],
            items: array_map(fn (array $i) => OrderItem::fromArray($i), $data['items']),
            reference: $data['reference'],
        );
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'first-name' => $this->firstName,
            'paid' => $this->paid,
            'items' => array_map(fn (OrderItem $i) => $i->toArray(), $this->items),
            'reference' => $this->reference,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

I ran those classes with declare(strict_types=1) against this payload, where the second item has no note key, the second price is the integer 10, and first-name is not a legal property name:

{"id":7,"first-name":"Ada","paid":true,"reference":"A-17","items":[{"sku":"X1","qty":2,"price":9.5},{"sku":"X2","qty":1,"price":10,"note":"gift"}]}
Enter fullscreen mode Exit fullscreen mode

What happened, from the actual run:

  • first-name landed in $firstName, and toArray() wrote it back as first-name.
  • The integer 10 went into the float $price property without an error and became 10.0. Under strict types PHP still allows an integer where a float is declared.
  • The union int|string kept the value's own type: "A-17" stayed a string, and a separate test with 5 stayed an int.
  • Assigning to a readonly property, $o->id = 9, threw Error: Cannot modify readonly property App\Data\Order::$id.
  • I confirmed that 2fa as $_2fa is a legal property name in PHP.

The round-trip claim has a catch

The page says it tests its output by loading the classes, building them with fromArray() and checking that toArray() returns the same JSON. That works for the sample you gave it. It does not mean every payload round-trips unchanged. In my test, the first item had no note key, and toArray() wrote "note":null for it. Here is the check I ran:

<?php

declare(strict_types=1);

use App\Data\Order;

$json = file_get_contents(__DIR__.'/sample.json');
$data = json_decode($json, true, flags: JSON_THROW_ON_ERROR);

$order = Order::fromArray($data);
$roundTrip = json_decode(json_encode($order->toArray()), true);

var_dump($roundTrip == $data);   // false if the sample had optional keys that were absent
Enter fullscreen mode Exit fullscreen mode

With the original payload it printed false, because the round trip added the note key. After adding "note":null to the first item in the input, it printed true. This matters if you forward data to another system that treats a missing key and a null differently. A related detail: json_encode(1.0) outputs 1 by default, and outputs 1.0 only with the JSON_PRESERVE_ZERO_FRACTION flag, so a float field that was 1.0 in the source can come back as 1 when re-encoded.

Errors you will see in production

These are the failures I triggered on purpose with the example classes under strict types:

  • A string where an int is declared. Passing "42" for id threw TypeError: App\Data\Order::__construct(): Argument #1 ($id) must be of type int, string given. APIs that quote their numbers will hit this.
  • A null where the type is not nullable. A null first-name threw a TypeError saying the argument must be of type string, null given.
  • A missing required key. With paid removed, PHP first emitted Warning: Undefined array key "paid" and then threw a TypeError ("must be of type bool, null given"). The warning comes from the array access, so a missing key looks like a confusing type error, and with a strict error handler it may become an exception first.

The fix for all three is to widen the sample JSON until it represents the real data: include records where fields are null or missing, and numbers that come as strings, then regenerate. For untrusted input, validate the payload first and call fromArray() afterwards. If you receive webhook data you do not control, wrap the call in a try/catch (TypeError) and reject the payload cleanly.

DTO or API Resource?

The page's explanation is that DTOs are for incoming data, such as API responses, webhooks and request payloads, while API Resources are for outgoing data, turning Eloquent models into API JSON. Choose the Resource output when you are building an endpoint and the JSON is the sample of what your API should return. A resource shaped like the order above looks like this:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'first-name' => $this->first_name,
            'paid' => (bool) $this->paid,
            'items' => OrderItemResource::collection($this->whenLoaded('items')),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

This resource is hand-written and was only syntax-checked; running it needs a Laravel application with an Order model and an OrderItemResource. The page says its generated resources are tested to return the same JSON, which I could not confirm.

Which PHP version option to pick

Pick the lowest version you actually deploy. On PHP 8.2 and later, a readonly class makes every property read-only, as the Order example shows. On 8.1 only individual properties can be readonly, and on 8.0 there is no readonly at all, so the objects are mutable:

<?php

namespace App\Data;

// PHP 8.1: readonly properties (class is not readonly)
final class OrderItem81
{
    public function __construct(
        public readonly string $sku,
        public readonly int $qty,
    ) {}
}

// PHP 8.0: plain typed properties (mutable)
final class OrderItem80
{
    public function __construct(
        public string $sku,
        public int $qty,
    ) {}
}
Enter fullscreen mode Exit fullscreen mode

Mutable DTOs are a real downside, because any code that holds the object can change it. If you are on 8.0, treat the objects as read-only by convention.

A short review checklist

  1. Paste a list of at least five realistic records, including ones with null and missing keys.
  2. Read each generated type against the API documentation, not only the sample. Money and IDs are the usual surprises.
  3. Look at each union type such as int|string. It often means the API is inconsistent, and you may prefer to normalize it in fromArray().
  4. Run a round-trip test like the one above on a few real payloads.
  5. Add a test with a deliberately broken payload to see which exception your code actually throws.

Related Dev Talk articles

Frequently asked questions

How do I convert JSON to a PHP class?

Paste the JSON into the generator, set the class name, namespace and PHP version, and copy the generated classes into the folder that matches the namespace. Then test fromArray() with real payloads.

Does it support nested objects and lists?

Yes. Each nested object becomes its own class, and lists are merged into one shape, with keys missing from some items made nullable.

What happens to keys like first-name?

They are converted to valid PHP property names such as $firstName, while fromArray() and toArray() keep the original key.

What is the difference between a DTO and an API Resource?

A DTO represents incoming data, while a Laravel API Resource shapes outgoing JSON from Eloquent models.

Why did I get a TypeError from fromArray()?

The payload had a value of a different type than the sample, such as a quoted number, a null, or a missing key. Regenerate the classes from a more representative sample.

Is my JSON uploaded to a server?

The page says it is converted in your browser and never uploaded. Remove secrets from payloads before pasting anyway.

update log

  • 26 November 2026: first version.
  • To recheck on each update: the tool's options and type rules, real generator output to replace my hand-written examples, and the PHP versions it targets.

Sources


Originally published on DEV Talk.

Top comments (0)