0

Currently, I'm looking for ways to deserialize entities from Change Feed Iterator content with System.Text.Json.

I found this example from the documentation, but it uses Newtonsoft.Json and I don't like an approach with JObject and JsonTextReader. Is there are any way to make it more properly and clean?

I've tried to make something like this, but my approach doesn't work.

ResponseMessage response = await iterator.ReadNextAsync(); 

var entities = await JsonSerializer.DeserializeAsync<IEnumerable<CosmosEntity1>>(response.Content);
dbc
  • 104,963
  • 20
  • 228
  • 340
  • What doesn't work in your code example? – NotFound Dec 13 '21 at 08:46
  • @404 it throws System.Text.Json.JsonException with a message "System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[ChangeFeedSubscriber.Entities.CosmosEntity1]". – CognitiveComplexity Dec 13 '21 at 08:50
  • Try to deserialize it into the List. But it would be easier to understand the problem if you show us your entities model and example of json from response content. – Repulse3 Dec 13 '21 at 08:58
  • @Repulse3 unfortunately still have an exception with a message "The JSON value could not be converted to System.Collections.Generic.List`1[ChangeFeedSubscriber.Entities.CosmosEntity1]". – CognitiveComplexity Dec 13 '21 at 09:01
  • What's the JSON you get when you do `var json = new StreamReader(response.Content).ReadToEnd();`? – NotFound Dec 13 '21 at 09:14
  • @404 { "_rid":"SsliAJBV7zU=", "Documents":[ { "id":"1", "name":"name2", "_rid":"SsliAJBV7zUBAAAAAAAAAA==", "_self":"dbs\/SsliAA==\/colls\/SsliAJBV7zU=\/docs\/SsliAJBV7zUBAAAAAAAAAA==\/", "_etag":"\"00000000-0000-0000-eff0-fd7a54a901d7\"", "_attachments":"attachments\/", "_ts":1639379635, "_lsn":4 } ], "_count":1 } – CognitiveComplexity Dec 13 '21 at 09:19
  • Also question: If your intent is to use System.Text.Json, why go through the Stream APIs? Have you tried just using System.Text.Json as serialization engine? https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/SystemTextJson – Matias Quaranta Dec 13 '21 at 16:36

1 Answers1

2

The response stream you get is not an IEnumerable of your documents but rather a class that contains the documents as one of its properties. Try creating the following class:

public class ExampleResponse
{
    public string _rid { get; set; }
    public List<CosmosEntity1> Documents { get; set; }
    public int _count { get; set; }
}

and deserialize your stream to that class.

NotFound
  • 5,005
  • 2
  • 13
  • 33