apimatic/jsonmapper
apimatic/jsonmapper is a lightweight PHP JSON-to-object mapper for converting API responses into typed models. It maps arrays/JSON to class properties with minimal setup, supports nested structures, and helps keep data hydration consistent across your application.
Start by installing the package via Composer:
composer require apimatic/jsonmapper
Create simple DTOs with typed properties (PHP 7.4+ recommended), then use JsonMapper to hydrate them directly from decoded JSON:
use Apimatic\JsonMapper\JsonMapper;
class User {
public int $id;
public string $name;
public array $tags;
}
$mapper = new JsonMapper();
$stdClass = json_decode('{"id": 42, "name": "Alice", "tags": ["dev", "api"]}');
$user = $mapper->map($stdClass, new User());
// $user is now a fully populated User instance
This is your first use case: converting raw API responses into typed DTOs without manual assignment.
JsonMapper becomes the central hydration engine across your SDK or service layer.public Address $address;) or arrays of objects (public array $users;). JsonMapper recursively constructs instances using type hints.JsonMapper’s fluent configuration methods for strictness, defaults, and coercion rules:
$mapper->configure()
->setMissingFieldPolicy(JsonMapper::MISSING_FIELD_IGNORE)
->setCoerceTypes(true)
->setDefaultValues(['status' => 'active']);
JsonMapper into services or repositories, or bind it as a singleton in a service provider for DI. Optionally wrap it in a helper trait or macroable facade for cleaner syntax.json_decode first) — ideal for testing or when consuming data from caches/db.ReflectionClass, but avoids heavy dependencies — however, ensure reflection extension is enabled (it’s built-in by default in standard PHP installs).JsonMapper::configure()->setAllowAccessToProtectedProperties(true).public string $name;), JsonMapper will not auto-inject default values unless explicitly configured via setDefaultValues() or nullable types (?string).setCoerceTypes(true), "42" becomes 42, but strict types (setCoerceTypes(false)) will throw on mismatched types — useful for enforcing API contract integrity.JsonMapper infers the element type from the property’s array type hint — make sure the property is typed correctly (e.g., public array $items; implies Item[]).setThrowExceptionOnInvalidJson(false) cautiously; prefer catching JsonMapperException explicitly to avoid silent failures during hydration.ReflectionClass instances or pre-warming the mapper for known DTOs — though for most Laravel apps, reflection overhead is negligible.How can I help you explore Laravel packages today?