<?phpusede\interaapps\jsonplus\JSONPlus;
usede\interaapps\jsonplus\serializationadapter\impl\JsonSerializationAdapter;
usede\interaapps\jsonplus\serializationadapter\impl\phpjson\PHPJsonSerializationAdapter;
$jsonPlus = JSONPlus::createDefault();
$obj = $jsonPlus->fromJson('{"test": "hello world"}');
echo$obj->test; // -> hello world// Enabling pretty printing$jsonPlus->setPrettyPrinting(true);
echo$jsonPlus->toJson($obj); // -> {"obj": "hello world"}/// Other drivers// Default if json_decode exists in JSONPlus::createDefault()$jsonPlus = newJSONPlus(newPHPJsonSerializationAdapter());
// Custom JSON implementation$jsonPlus = newJSONPlus(newJsonSerializationAdapter());<?phpusede\interaapps\jsonplus\JSONPlus;
usede\interaapps\jsonplus\JSONModel;
usede\interaapps\jsonplus\attributes\Serialize;
usede\interaapps\jsonplus\attributes\ArrayType;
class Organisation {
publicstring$name;
}
enum UserType {
caseADMIN;
caseMEMBER;
}
class User {
use JSONModel;
publicint$id;
#[Serialize("first_name")]
publicstring$firstName;
#[Serialize(hidden: true)]
publicstring$password;
public ?Organisation$organisation;
// Set Type for array:
#[ArrayType(User::class)]
publicarray$friends;
publicUserType$type = UserType::MEMBER;
}
$json = '{ "id": 12343, "first_name": "Jeff", "organisation": { "name": "InteraApps" }, "friends": [ { "id": 3245, "first_name": "John", "friends": [] } ], "type": "MEMBER"}';
// Decoding the JSON$user = User::fromJson($json);
echo"Hello. My name is ".$user->first_name.", I have the ID ".$user->id
."and I'm in the organisation ".$user->organisation->name."\n";
foreach ($user->friendsas$friend) {
echo"One of my friends: ".$friend->name."\n";
}
// Encoding to JSONecho$user->toJson();
// Decode typed JSON-array$jsonPlus = JSONPlus::createDefault();
$users = $jsonPlus->fromMappedArrayJson('[...]', User::class);
foreach ($usersas$user) {}Tip: If you are using PHPStorm or any other intelligent IDE you might add PHP-Docs to some fields.
For Typed Arrays:
/** * @var array<User> */
#[ArrayType(User::class)]
private array $myArray;uppm install interaapps/jsonplus
composer require interaapps/jsonplus