1. Go to this page and download the library: Download s-mcdonald/phpjson library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
s-mcdonald / phpjson example snippets
class User
{
#[JsonProperty]
public string $name;
#[JsonProperty]
public array $phoneNumbers;
private int $creditCard;
}
$serializer = new JsonSerializer();
echo $serializer->serialize($user);
echo Json::serialize($user); // outputs json
class User
{
#[JsonProperty('userName')]
public string $name;
#[JsonProperty('numbers')]
public array $phoneNumbers;
private int $creditCard;
}
class User
{
#[JsonProperty]
public function authenticator(): string
{
return $this->authenticator;
}
#[JsonProperty('creditCardNumber')]
public function getCreditCard(): int
{
return $this->creditCard;
}
}
class ParentClass
{
#[JsonProperty('userName')]
public string $name;
#[JsonProperty('child')]
public ChildClass $someChild;
}
class ChildClass
{
public function __construct(
#[JsonProperty('childProp')]
private string $childProperty,
){
}
}
$sut = new ParentClass();
$sut->name = 'fu';
$sut->someChild = new ChildClass("bar");
enum Status
{
case Enabled;
case Disabled;
}
echo Json::serialize(Status::Enabled);
enum Status: int
{
case Enabled = 10;
case Disabled = 20;
}
echo Json::serialize(Status::Enabled);
class
{
#[JsonProperty(type: new StringType())]
public float $myNumber = 123.456;
#[JsonProperty(type: new IntegerType())]
public float $myNumber2 = 123.456;
}
class MyUser
{
public string $name;
public int $age;
public bool $isActive;
}
class MyUser
{
#[JsonProperty('name')]
public string $userName;
public int $age;
public bool $isActive;
#[JsonProperty('name')]
public function setUserName(string $value): void
{
$this->userName = 'foo: ' . $value;
}
}