PHP code example of greenskies / json

1. Go to this page and download the library: Download greenskies/json 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/ */

    

greenskies / json example snippets


$jsonString = '{"good":true}';

$decoded = Json::Decode($jsonString);

// $decoded->good = true

$jsonString = '{"good":true}';
$options = [
    Json::ASSOCIATIVE => true,
];
$decoded = Json::Decode($jsonString, $options);
// $decoded['good'] = true


$jsonString = '{"processRefund": "true", "refundAmount": "17"}'
                             
$schema = (object) [
    "type"=>"object",
    "properties"=>(object)[
        "processRefund"=>(object)[
            "type"=>"boolean"
        ],
        "refundAmount"=>(object)[
            "type"=>"number"
        ]
    ]
];

$options = [
    Json::VALIDATOR => [
        Json::JSON_SCHEMA => $schema,
        Json::CONSTRAINTS => Constraint::CHECK_MODE_COERCE_TYPES,
    ],
];

$decoded = Json::Decode($jsonString, $options);

$jsonString = '{"id": 1, "name": "John Doe"}';

$options = [
    Json::DECODER => [
        Json::CLASS_NAME => Person::class,       
    ],
];
$decoded = Json::Decode($jsonString, $options);

$jsonString = '[{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Doe"}]';

$options = [
    Json::DECODER => [
        Json::CLASS_NAME => Person::class,
        Json::DECODE_MULTIPLE => true,
    ],
];

$personArray = Json::Decode($jsonString, $options);