Is there a way to cast the Microsoft.Azure.Documents.Document
object to my class type?
I've written an Azure Function class, with a CosmosDBTrigger
. The trigger receives an array of Microsoft.Azure.Documents.Document
. I like having that Document
class so that I can access the meta data about the record itself, but I also would like to interact with my data from my class type in a static way.
I see the JSON representation of my data when I call ToString
. Should I manually convert that JSON to my class type using Newtonsoft?
If you need to map your Document
to your POCO in the function then the easiest way to do that is what you suggested.
Call the document.Resource.ToString()
method and use DeserializeObject
from JSON.NET or the json library you prefer. JSON.NET is recommended however as Microsoft's CosmosDB libraries use it as well.
Your mapping call will look like this:
var yourPoco = JsonConvert.DeserializeObject<YourPocoType>(document.Resource.ToString())
You can simply do a .ToString()
in the Microsoft.Azure.Documents.Document
class.
This class inherits from the Microsoft.Azure.Documents.JsonSerializable
class that overrides the .ToString()
method.
Here below is an example of deserializing the Document
class to my Car.cs
POCO using the new high-performant System.Text.Json
Namespace:
Car car = JsonSerializer.Deserialize<Car>(document.ToString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With