为DocumentDb设置自定义json转换器 [英] Setting a custom json converter for DocumentDb
问题描述
我正在使用类型化的DocumentQuery从Azure DocumentDb的集合中读取文档.
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
因为我没有找到设置neccesarry自定义json转换器的方法,所以抛出了这个例子:
Because I do not find a way how I can set the neccesarry custom json converter, it throws this exeption:
无法创建类型AbstractObject的实例.类型是 接口或抽象类,无法实例化.
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没有任何SerializerSettings.所以问题是,在将json数据反序列化到我的模型时,如何告诉DocumentDB客户端必须使用自定义转换器?
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?
推荐答案
您可以将[JsonConverter(typeof(MyAbstractConverter))]
添加到模型类中.
You can add [JsonConverter(typeof(MyAbstractConverter))]
to your model class.
这是带有自定义Json设置的示例模型类:
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; }
}
}
这篇关于为DocumentDb设置自定义json转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!