Skip to main content

JSON serialization

Quantities implement JsonSerializable, so they can be passed directly to json_encode(). A matching fromJson() factory reconstructs an instance from the decoded data.

Encoding

use Renfordt\UnitLib\Length;

$length = new Length(100, 'cm');
$json = json_encode($length);

The encoded form contains both the original and native values, plus the fully qualified class name:

{
"value": 100,
"unit": "cm",
"nativeValue": 1,
"nativeUnit": "m",
"class": "Renfordt\\UnitLib\\Length"
}

Decoding

fromJson() takes the decoded array and reconstructs the quantity from the class, value, and unit fields:

use Renfordt\UnitLib\PhysicalQuantity;

$data = json_decode($json, true);
$restored = PhysicalQuantity::fromJson($data);

$restored->originalValue; // 100.0
$restored->toUnit('m'); // 1.0

The round trip preserves the original value and unit, which means the reconstructed instance is equivalent to the original.

Validation

fromJson() throws InvalidArgumentException when:

  • any of class, value, or unit is missing,
  • class is not a string,
  • the named class does not exist, or
  • the named class is not a subclass of PhysicalQuantity.

These checks prevent arbitrary class names in the input from being instantiated.