microsoft/kiota-serialization-json
PHP JSON serialization library for Kiota-generated SDKs. Provides JSON parse/serialize support for API request and response payloads in Kiota PHP projects. Install via Composer: microsoft/kiota-serialization-json.
Installation:
composer require microsoft/kiota-serialization-json
Ensure your composer.json requires ^2.0.2 (or latest stable) and PHP 8.2+ (due to breaking changes in v2.0.0).
Kiota Integration:
The package is designed to work with Kiota. If you’re using a Kiota-generated client (e.g., from @microsoft/kiota-http), register the JSON serializer in your client configuration:
use Microsoft\Kiota\Serialization\Json\JsonSerializer;
$serializer = new JsonSerializer();
$client = new YourGeneratedClient();
$client->setSerializer($serializer);
First Use Case: Serialize/deserialize a simple object:
$data = new \stdClass();
$data->name = "Test";
$data->value = 42;
// Serialize
$json = $serializer->serializeObject($data);
// Deserialize
$deserialized = $serializer->deserializeObject($json, \stdClass::class);
Request/Response Handling: Use the serializer to convert between PHP objects and JSON for API calls:
$requestInfo = new YourRequestModel();
$serializer->serializeRequestInformation($requestInfo);
$response = $client->request($requestInfo);
$responseData = $serializer->deserializeObject($response->getContent(), YourResponseModel::class);
Complex Types: Handle nested/composed types (e.g., arrays, custom objects) via Kiota’s type system:
$complexData = new YourComplexModel();
$complexData->items = [new ItemModel(), new ItemModel()];
$json = $serializer->serializeObject($complexData);
DateTime Handling:
The serializer supports DateTime/DateTimeImmutable out-of-the-box:
$model = new YourModel();
$model->createdAt = new DateTime();
$json = $serializer->serializeObject($model);
Streaming: Deserialize directly to streams (e.g., for large files):
$stream = fopen('output.json', 'w');
$serializer->deserializeObjectToStream($json, $stream, YourModel::class);
Laravel Service Providers: Bind the serializer to Laravel’s container for dependency injection:
$this->app->bind(JsonSerializer::class, function () {
return new JsonSerializer();
});
Then inject it into services:
public function __construct(private JsonSerializer $serializer) {}
Middleware: Use the serializer in middleware to transform requests/responses:
public function handle($request, Closure $next) {
$response = $next($request);
if ($response->isSuccessful()) {
$data = $this->serializer->deserializeObject($response->getContent(), YourModel::class);
$response->setContent($this->serializer->serializeObject($data));
}
return $response;
}
Testing: Mock the serializer for unit tests:
$mockSerializer = $this->createMock(JsonSerializer::class);
$mockSerializer->method('serializeObject')->willReturn('{"test": "value"}');
$client = new YourClient($mockSerializer);
PHP Version Requirement:
microsoft/kiota-serialization-json:1.5.2 if stuck on PHP 8.1 (but unsupported).Type Casting:
int to float) to prevent logical bugs. Ensure your API contracts match PHP types exactly.42 will deserialize to a PHP int, not float.Null Handling:
null values by default. Use JsonParseNode::getObjectValue() carefully to avoid missing data.null in your models if needed.DateTime Precision:
P-1Y) may fail. Use DateTime objects instead of ISO strings for reliability.Performance:
Validation Errors:
Use JsonParseNode::getObjectValue() to inspect raw JSON before deserialization:
$node = $serializer->parse($json);
$value = $node->getObjectValue(); // Raw PHP array
Custom Serialization:
Extend JsonSerializer to handle custom types:
class CustomSerializer extends JsonSerializer {
public function serializeObject($object) {
if ($object instanceof YourCustomType) {
return json_encode(['custom' => $object->getValue()]);
}
return parent::serializeObject($object);
}
}
Logging: Log serialized/deserialized payloads for debugging:
$serialized = $serializer->serializeObject($data);
\Log::debug('Serialized payload:', ['json' => $serialized]);
Custom Formatters:
Override JsonSerializer::getStringValue() or JsonSerializer::getObjectValue() for custom logic:
protected function getStringValue(JsonParseNode $node): string {
$value = parent::getStringValue($node);
return strtoupper($value); // Example: Force uppercase
}
Binary Data:
Use JsonParseNode::getStreamValue() for binary fields (e.g., base64-encoded blobs):
$node = $serializer->parse($json);
$stream = $node->getStreamValue('binaryField');
Error Handling:
Catch JsonSerializationException for malformed JSON:
try {
$serializer->deserializeObject($invalidJson, YourModel::class);
} catch (JsonSerializationException $e) {
\Log::error('Deserialization failed:', ['error' => $e->getMessage()]);
}
Kiota Abstractions:
The package relies on microsoft/kiota-abstractions. Ensure compatibility by checking the Kiota PHP releases.
How can I help you explore Laravel packages today?