In an ASP.NET Core web api I am using System.Text.Json
. I am also using the Cosmos DB Change Feed Pull Method to process changed items. I need to examine the type
property of each item to determine the type to de-serialize the item to. In order to do this, I am using GetChangeFeedStreamIterator
. Working off the following sample code:
FeedIterator feedIterator = this.Container.GetChangeFeedStreamIterator(
ChangeFeedStartFrom.Beginning(),
ChangeFeedMode.Incremental,
options);
while (feedIterator.HasMoreResults)
{
using (ResponseMessage response = await feedIterator.ReadNextAsync())
{
if (response.StatusCode == NotModified)
{
// No new changes
// Capture response.ContinuationToken and break or sleep for some time
}
else
{
using (StreamReader sr = new StreamReader(response.Content))
using (JsonTextReader jtr = new JsonTextReader(sr))
{
JObject result = JObject.Load(jtr);
}
}
}
}
I came up with this:
FeedIterator feedIterator = _entities.GetChangeFeedStreamIterator(startFrom, ChangeFeedMode.Incremental);
var result = new ChangedEntitiesResult();
while (feedIterator.HasMoreResults) {
using ResponseMessage response = await feedIterator.ReadNextAsync();
if (response.StatusCode == HttpStatusCode.NotModified) {
result.ContinuationToken = response.ContinuationToken;
break;
} else {
using StreamReader resultStreamReader = new StreamReader(response.Content);
using JsonTextReader resultJsonTextReader = new JsonTextReader(resultStreamReader);
var resultJObject = JObject.Load(resultJsonTextReader);
JArray documents = (JArray)resultJObject["Documents"];
foreach (JObject document in documents) {
string entityType = (string)document["type"];
var entity = _entityFactory.GetNewEntityDtoInstance(entityType);
_serializer.Populate(document.CreateReader(), entity);
result.Entities.Add(entity);
}
}
}
The code above works as expected but I am running into issues with nested json objects elsewhere in the application. The conflict is between objects serialized with System.Text.Json
and deserialized with Newtonsoft
. So either I switch completely over to Newtonsoft
, or I convert the above code to use System.Text.Json
.
Can I accomplish the above with System.Text.Json or should I just switch the whole project to Newtonsoft?
I am open to other suggestions like approaching the problem of identifying the type and instantiating and hydrating the correct class some other way.