Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Kiota Serialization Json Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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).

  2. 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);
    
  3. 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);
    

Implementation Patterns

Core Workflows

  1. 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);
    
  2. 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);
    
  3. DateTime Handling: The serializer supports DateTime/DateTimeImmutable out-of-the-box:

    $model = new YourModel();
    $model->createdAt = new DateTime();
    $json = $serializer->serializeObject($model);
    
  4. Streaming: Deserialize directly to streams (e.g., for large files):

    $stream = fopen('output.json', 'w');
    $serializer->deserializeObjectToStream($json, $stream, YourModel::class);
    

Integration Tips

  • 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);
    

Gotchas and Tips

Pitfalls

  1. PHP Version Requirement:

    • v2.0.0+ requires PHP 8.2+. Downgrading to v1.x is not recommended due to security fixes.
    • Workaround: Use microsoft/kiota-serialization-json:1.5.2 if stuck on PHP 8.1 (but unsupported).
  2. Type Casting:

    • The serializer avoids casting (e.g., int to float) to prevent logical bugs. Ensure your API contracts match PHP types exactly.
    • Example: A JSON 42 will deserialize to a PHP int, not float.
  3. Null Handling:

    • Collections (e.g., arrays) exclude null values by default. Use JsonParseNode::getObjectValue() carefully to avoid missing data.
    • Fix: Explicitly check for null in your models if needed.
  4. DateTime Precision:

    • Negative date periods (e.g., P-1Y) may fail. Use DateTime objects instead of ISO strings for reliability.
  5. Performance:

    • Parse node allocations were optimized in v2.0.1. If profiling shows high memory usage, ensure you’re not recursively serializing/deserializing large objects.

Debugging Tips

  • 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]);
    

Extension Points

  1. 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
    }
    
  2. Binary Data: Use JsonParseNode::getStreamValue() for binary fields (e.g., base64-encoded blobs):

    $node = $serializer->parse($json);
    $stream = $node->getStreamValue('binaryField');
    
  3. Error Handling: Catch JsonSerializationException for malformed JSON:

    try {
        $serializer->deserializeObject($invalidJson, YourModel::class);
    } catch (JsonSerializationException $e) {
        \Log::error('Deserialization failed:', ['error' => $e->getMessage()]);
    }
    
  4. Kiota Abstractions: The package relies on microsoft/kiota-abstractions. Ensure compatibility by checking the Kiota PHP releases.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony