从MongoDB反序列化可枚举为ICollection <t> </t>

时间:2013-03-24 19:42:23

标签: c# mongodb serialization bson tweetsharp

我有以下问题反序列化MongoDB中的TwitterStatus类,这是使用MongoDB C#驱动程序1.8.0.124和TweetSharp 2.0的失败单元测试:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System.Linq;
using TweetSharp;

namespace DS.Model.Tests
{
    [TestClass]
    public class TestMongoSerialization
    {
        [TestMethod]
        public void CanDeserializeTwitterEntitiesFromMongoDB()
        {
            var server = new MongoClient().GetServer();
            MongoDatabase db = server.GetDatabase("test");
            var tweets = db.GetCollection<TwitterStatus>("tweetSerialized");

            var tweet = Newtonsoft.Json.JsonConvert.DeserializeObject<TwitterStatus>(tweetWithTwitterEntityiesSerialized);
            Assert.AreEqual(1, tweet.Entities.Count());
            Assert.AreEqual(TwitterEntityType.Url, tweet.Entities.First().EntityType);
            tweets.Save(tweet);
            Assert.AreEqual(1, tweets.FindAll().Count()); 

            var tweetFromMango = tweets.FindOne(Query<TwitterStatus>.EQ(s => s.Id, 315278676398858240));
            Assert.AreEqual(TwitterEntityType.Url, tweetFromMango.Entities.First().EntityType); // throws exception [1]
        }

        string tweetWithTwitterEntityiesSerialized = @"{""Id"":315278676398858240,""Text"":""TeePublic Funds 22 Designs "",""RetweetedStatus"":null,""created_at"":""2013-03-23T01:47:48Z"",""geo"":null,""Entities"":{""user_mentions"":[],""hashtags"":[],""urls"":[{""url"":""http://t.co/rBGN46rua7"",""expanded_url"":""http://zite.to/10uCED9"",""indices"":[71,93],""EntityType"":2}],""media"":[]},""possibly_sensitive"":false,""Place"":null}";

    }
}

抛出的异常是Enumerable class TwitterEntities does not implement ICollection<T> so it can't be deserialized,下面是完整的堆栈跟踪。

完整堆栈跟踪:

System.IO.FileFormatException: An error occurred while deserializing the Entities property of class TweetSharp.TwitterStatus: 
Enumerable class TwitterEntities does not implement ICollection<T> so it can't be deserialized. ---> MongoDB.Bson.BsonSerializationException: Enumerable class TwitterEntities does not implement ICollection<T> so it can't be deserialized.
Result StackTrace:  
at MongoDB.Bson.Serialization.Serializers.EnumerableSerializer`1.CreateInstance(Type type)
   at MongoDB.Bson.Serialization.Serializers.EnumerableSerializer`1.Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
   at MongoDB.Bson.Serialization.BsonClassMapSerializer.DeserializeMemberValue(BsonReader bsonReader, BsonMemberMap memberMap)
 --- End of inner exception stack trace ---
    at MongoDB.Bson.Serialization.BsonClassMapSerializer.DeserializeMemberValue(BsonReader bsonReader, BsonMemberMap memberMap)
   at MongoDB.Bson.Serialization.BsonClassMapSerializer.Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
   at MongoDB.Bson.Serialization.BsonClassMapSerializer.Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
   at MongoDB.Bson.Serialization.BsonSerializer.Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)

如何在没有此异常的情况下从mongoDB反序列化TweetStatus类? 作为参考,有the TwitterEntity classes

1 个答案:

答案 0 :(得分:2)

TwitterStatus有一个属性

public virtual TwitterEntities Entities

,定义为

public class TwitterEntities : IEnumerable<TwitterEntity>

现在,当反序列化JSon.NET时,会生成 TwitterEntities 的实例,然后尝试用 TwitterEntity 项填充它。但要做到这一点,它需要一个Add方法, IEnumerable 不提供。 但是ICollection(T)确实提供了添加方法,这就是它要求ICollection(T)的原因。

但是如果您使用的是MongoDb IMO,则不应直接进行任何JSON转换。您应该只有简单的POCO类,MongoDb驱动程序将自动为您自动处理这些类实例的序列化。

这就是使用文档数据库的美妙。