Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast Azure DocumentDB Document class to my POCO class?

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?

like image 746
Ryan Avatar asked Jul 18 '18 21:07

Ryan


Video Answer


2 Answers

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())

like image 188
Nick Chapsas Avatar answered Nov 15 '22 19:11

Nick Chapsas


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

like image 24
John Avatar answered Nov 15 '22 20:11

John