7

I am using a typed DocumentQuery to read documents from a collection of an Azure DocumentDb.

from f in client.CreateDocumentQuery<MyModel>(Collection.SelfLink) select f

Because I do not find a way how I can set the neccesarry custom json converter, it throws this exeption:

Could not create an instance of type AbstractObject. Type is an interface or abstract class and cannot be instantiated.

Usually you do something like this to make it work:

var settings = new JsonSerializerSettings();
settings.Converters.Add(new MyAbstractConverter());
client.SerializerSettings = settings;

DocumentClient doesn't have any SerializerSettings. So the question is, how can I tell the DocumentDB client that it must use a custom converter when deserializing the json data to my model?

dixus
  • 478
  • 4
  • 15
  • 3
    Have you tried adding a `[JsonConverter(typeof(MyAbstractConverter))]` attribute to your abstract model class? – Brian Rogers Dec 11 '14 at 22:35
  • The Attribute works :) I am getting another exeption, but this is not about the abstract instance. Thank you! – dixus Dec 12 '14 at 06:39

2 Answers2

5

You can add [JsonConverter(typeof(MyAbstractConverter))] to your model class.

Here's an example model class with custom Json settings:

namespace DocumentDB.Samples.Twitter
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using DocumentDB.Samples.Shared.Util;
    using Newtonsoft;
    using Newtonsoft.Json;

    /// <summary>
    /// Represents a user.
    /// </summary>
    public class User
    {
        [JsonProperty("id")]
        public long UserId { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("screen_name")]
        public string ScreenName { get; set; }

        [JsonProperty("created_at")]
        [JsonConverter(typeof(UnixDateTimeConverter))]
        public DateTime CreatedAt { get; set; }

        [JsonProperty("followers_count")]
        public int FollowersCount { get; set; }

        [JsonProperty("friends_count")]
        public int FriendsCount { get; set; }

        [JsonProperty("favourites_count")]
        public int FavouritesCount { get; set; }
    }
}
Andrew Liu
  • 8,045
  • 38
  • 47
  • What's the reference of UnixDateTimeConverter? – Can Ürek Apr 04 '16 at 15:26
  • 1
    Sorry, should have provided a link earlier: https://github.com/Azure/azure-documentdb-dotnet/blob/master/samples/code-samples/Shared/Util/UnixDateTimeConverter.cs – Andrew Liu Apr 13 '16 at 00:37
  • @AndrewLiu what does that attribute actually do, does it add things to the serialised file in DocumentDb? – m1nkeh Jan 23 '18 at 21:16
3

The latest CosmosDB SDK now includes support for JsonSerializerSettings so you don't have to use JsonConverter anymore, you can use your own ContractResolver. See related SO post.

SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173