Microsoft Kiota JSON Serialization
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
- breaking Starting with version 1.10.0, support for Python 3.9 has been dropped. Ensure your environment uses Python 3.10 or newer.
- gotcha This library is designed specifically for serializing and deserializing models that implement the `microsoft_kiota_abstractions.serialization.Parsable` interface, typically generated by the Kiota OpenAPI SDK generator. It is not intended as a general-purpose JSON serialization library for arbitrary Python objects.
- gotcha When serializing a root object using `writer.write_object_value()`, the key parameter should typically be `None` or an empty string, especially if the resulting JSON should be a single object. Providing a non-None, non-empty key will wrap the object under that key.
- gotcha This library relies heavily on `microsoft-kiota-abstractions`. If you install `microsoft-kiota-serialization-json` directly, ensure `microsoft-kiota-abstractions` is also installed (it's a dependency, but manual inspection might be needed if dependency resolution issues arise).
Install
-
pip install microsoft-kiota-serialization-json
Imports
- JsonSerializationWriterFactory
from microsoft_kiota_serialization_json import JsonSerializationWriterFactory
- JsonParseNodeFactory
from microsoft_kiota_serialization_json import JsonParseNodeFactory
- Parsable
from microsoft_kiota_abstractions.serialization import Parsable
Quickstart
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!")