我试图让Cosmos DB .NET SDK v1.19.1使用Json.net序列化设置自动将对象反序列化为正确的类型。除了查询文档时,这似乎工作正常。以下面的代码为例:
public abstract class Shape
{
public int Area { get; set; }
}
public class Square : Shape { }
public class Triangle : Shape { }
public class Entity
{
public string Id { get; set; }
public string Name { get; set; }
public Shape Shape { get; set; }
}
static void Main(string[] args)
{
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
TypeNameHandling = TypeNameHandling.Auto
};
var database = "db";
var collection = "coll";
var client = new DocumentClient(new Uri("https://docdburi.documents.azure.com:443/"), "supersecretkey", JsonConvert.DefaultSettings());
var entity = new Entity() { Id = "testid", Name = "John Doe", Shape = new Square() { Area = 5 } };
var doc = client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, collection), entity).Result;
entity = client.ReadDocumentAsync<Entity>(UriFactory.CreateDocumentUri(database, collection, entity.Id)).Result;
// all good so far ... next line throws serialization exception on abstract shape type
var result = client.CreateDocumentQuery<Entity>(UriFactory.CreateDocumentCollectionUri(database, collection), new FeedOptions() { MaxItemCount = 1 })
.Where(x => x.Id == entity.Id).AsDocumentQuery()
.ExecuteNextAsync<Entity>().Result;
文档在Cosmos DB中创建,并且形状上的$ type属性符合预期,并且检索文档工作正常。只有当我尝试查询抛出异常的文档时。关于如何使其发挥作用的任何想法?
关于如何最好地处理抽象类型的任何其他建议?我有一个相当深的对象图,有几层抽象类型。
答案 0 :(得分:0)
这个助手通常对我有用:
public abstract class SerializableObject<T>
{
public static T FromJObject(JObject jObject) =>
Parse($"{jObject}");
public static T Parse(string json) =>
JsonConvert.DeserializeObject<T>(json,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
public JObject ToJObject() => JObject.Parse(ToJson());
public string ToJson() =>
JsonConvert.SerializeObject(this, Formatting.Indented,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
}
现在继承你的Entity
课程:
public class Entity : SerializableObject<Entity>
{
public string Id { get; set; }
public string Name { get; set; }
public Shape Shape { get; set; }
}
并尝试使用JObject
以某种方式查询它:
var result = client.CreateDocumentQuery<JObject>(
UriFactory.CreateDocumentCollectionUri(database, collection),
new FeedOptions() { MaxItemCount = 1 })
.Where(x => x.Id == entity.Id)
.AsEnumerable()
.Select(Entity.FromJObject)
.FirstOrDefault();