Search code examples
azure-cosmosdbjson-deserializationjson-serializationazure-cosmosdb-tables

CosmosDB per item ttl setting throwing exception: Cannot deserialize the current JSON object


I am following this documentation to set per item ttl to a CosmosDB table entries. But when I add a field name ttl in the entity class I am facing the below error while making Insert/Replace calls:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Nullable`1[System.Int32]' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly. To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'ttl.$t', line 1, position 109.

public class MyEntity : TableEntity
{
    public string Prop { get; set; }
    
    [JsonProperty(PropertyName = "ttl", NullValueHandling = NullValueHandling.Ignore)]
    public int? ttl { get; set; }

    public MyEntity(
       string pk,
       string rk,
       string prop)
    {
        this.PartitionKey = pk;
        this.RowKey = rk;
        this.Prop =prop;
        this.ttl = -1;
    }
}

How can this be solved?


Solution

  • UPDATE

    Follow the offical document and update my Items in Azure Cosmos DB Emulator. Items will be deleted according to the expected value of TTL.

    while (feedIterator.HasMoreResults)
    {
        foreach (var item in await feedIterator.ReadNextAsync())
        {
           item.ttl = 10;
           await container.UpsertItemAsync<MyEntity>(item, new PartitionKey(item.address));
        }
    }
    

    enter image description here

    Hope my answer can help you.

    enter image description here

    using System;
    using System.Threading.Tasks;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Net;
    using System.Linq;
    using Newtonsoft.Json;
    using Microsoft.Azure.Cosmos;
    using Microsoft.Azure.Cosmos.Table;
    
    namespace CosmosGettingStartedTutorial
    {
        class Program
        {
            // <Main>
            public static async Task Main(string[] args)
            {
                try
                {
                    Console.WriteLine("Beginning operations...\n");
                    CosmosClient client = new CosmosClient("https://localhost:8081/", "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
                    Database database = await client.CreateDatabaseIfNotExistsAsync("ToDoList");
                    Container container = database.GetContainer("jason");
                    // Add for an item
                    QueryDefinition queryDefinition = new QueryDefinition("select * from c ");
                    FeedIterator<MyEntity> feedIterator = container.GetItemQueryIterator<MyEntity>(queryDefinition, null, new QueryRequestOptions() { PartitionKey = new PartitionKey("address0") });
                    int count = 0;
                    while (feedIterator.HasMoreResults)
                    {
                        foreach (var item in await feedIterator.ReadNextAsync())
                        {
                            if (item.id == "0")
                            {
                                Console.WriteLine("id equal 0  is exist: id = " + item.id);
                                Console.WriteLine("We will change id='test" + item.id + "'");
                                Console.WriteLine("pls wait ,will update ");
                                item.id = "test" + item.id;
                                await container.UpsertItemAsync<MyEntity>(item, new PartitionKey(item.address));
                            }
                            count++;
                        }
                    }
    
                    int num = count + 5;
                    for (int i = count; i < num; i++)
                    {
                        MyEntity entity = new MyEntity(i.ToString(), i.ToString(), i.ToString());
                        entity.id = i.ToString();
                        entity.address = "address0";
                        await container.CreateItemAsync<MyEntity>(entity, new PartitionKey(entity.address));
                    }
                }
                catch (CosmosException de)
                {
                    Exception baseException = de.GetBaseException();
                    Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e);
                }
                finally
                {
                    Console.WriteLine("End of demo, press any key to exit.");
                    Console.ReadKey();
                }
            }
            public class MyEntity : TableEntity
            {
                public string Prop { get; set; }
    
                [JsonProperty(PropertyName = "ttl", NullValueHandling = NullValueHandling.Ignore)]
                public int? ttl { get; set; }
    
                public MyEntity(string pk, string rk, string prop)
                {
                    this.PartitionKey = pk;
                    this.RowKey = rk;
                    this.Prop = prop;
                    this.ttl = -1;
                }
                public string address { get; set; }
                public string id { get; set; }
            }
        }
    }