Microsoft Kiota JSON Serialization

1.10.1 · active · verified Thu Apr 09

microsoft-kiota-serialization-json provides JSON serialization and deserialization capabilities for Kiota-generated Python SDKs. It includes factories for creating JSON serialization writers and parse nodes, enabling the conversion of `Parsable` objects to and from JSON format. The library is part of the larger Microsoft Kiota ecosystem and is currently at version 1.10.1, with frequent synchronized releases across its components.

Warnings

Install

Imports

Quickstart

This example demonstrates how to serialize a `Parsable` object to JSON and then deserialize it back using `JsonSerializationWriterFactory` and `JsonParseNodeFactory`. It defines a simple `MyModel` class implementing the `Parsable` interface from `microsoft-kiota-abstractions`.

import io
from typing import Callable, Dict, Optional
from uuid import UUID

from microsoft_kiota_abstractions.serialization import Parsable, ParseNode, SerializationWriter
from microsoft_kiota_serialization_json import JsonParseNodeFactory, JsonSerializationWriterFactory

class MyModel(Parsable):
    """A simple model for demonstration."""
    def __init__(self) -> None:
        self._id: Optional[UUID] = None
        self._name: Optional[str] = None
        self.additional_data: Dict[str, object] = {}

    @property
    def id(self) -> Optional[UUID]:
        return self._id

    @id.setter
    def id(self, value: Optional[UUID]) -> None:
        self._id = value

    @property
    def name(self) -> Optional[str]:
        return self._name

    @name.setter
    def name(self, value: Optional[str]) -> None:
        self._name = value

    def get_field_deserializers(self) -> Dict[str, Callable[[ParseNode], None]]:
        """Gets the deserialization information for the current model."""
        return {
            "id": lambda n: setattr(self, 'id', n.get_uuid_value()),
            "name": lambda n: setattr(self, 'name', n.get_str_value()),
        }

    def serialize(self, writer: SerializationWriter) -> None:
        """Serializes properties of the current model into a writer."""
        writer.write_uuid_value("id", self.id)
        writer.write_str_value("name", self.name)
        writer.write_additional_data_value(self.additional_data)

# --- Usage Example ---

# 1. Create a model instance
my_object = MyModel()
my_object.id = UUID("12345678-1234-5678-1234-567812345678")
my_object.name = "Test Item"
my_object.additional_data["status"] = "active"

# 2. Serialize the model to JSON
writer_factory = JsonSerializationWriterFactory()
# Use 'application/json' for JSON content type
with writer_factory.get_serialization_writer("application/json") as writer:
    # Pass None as the key for the root object
    writer.write_object_value(None, my_object)
    serialized_content_bytes = writer.get_serialized_content()

print("Serialized JSON:")
print(serialized_content_bytes.decode('utf-8'))

# 3. Deserialize the JSON back into a model instance
parse_node_factory = JsonParseNodeFactory()
with parse_node_factory.get_parse_node("application/json", serialized_content_bytes) as parse_node:
    deserialized_object = parse_node.get_object_value(MyModel)

print("\nDeserialized object:")
print(f"ID: {deserialized_object.id}")
print(f"Name: {deserialized_object.name}")
print(f"Additional data: {deserialized_object.additional_data}")

# Verify deserialization
assert deserialized_object.id == my_object.id
assert deserialized_object.name == my_object.name
assert deserialized_object.additional_data["status"] == my_object.additional_data["status"]
print("\nSerialization and deserialization successful!")

view raw JSON →