Skip to content

Examples

Greg Bowler edited this page Jun 20, 2023 · 3 revisions

1. Build an object up and convert it to JSON

use Gt\DataObject\DataObject;

$obj = (new DataObject())
	->with("name", "Cody")
	->with("colour", "orange")
	->with("food", [
		"biscuits",
		"mushrooms",
		"corn on the cob",
	]);

echo json_encode($obj), PHP_EOL;

Output:

{"name":"Cody","colour":"orange","food":["biscuits","mushrooms","corn on the cob"]}

2. Build a DataObject from a JSON string

use Gt\DataObject\DataObjectBuilder;

$jsonString = '{"name":"Cody","colour":"orange","food":["biscuits","mushrooms","corn on the cob"]}';

$builder = new DataObjectBuilder();
$obj = $builder->fromObject(json_decode($jsonString));

echo "Hello, ",
	$obj->getString("name"),
	"! Your favourite food is ",
	$obj->getArray("food")[0],
	PHP_EOL;

Output:

Hello, Cody! Your favourite food is biscuits
Clone this wiki locally