public partial class Sentence : IBsonSerializable
{
public static int idSum;
public bool GetDocumentId(out object id, out Type idNominalType, out IIdGenerator idGenerator)
{
id = this.Id = idSum++;
idNominalType = typeof(int);
idGenerator = null;
return true;
}
public void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options)
{
bsonWriter.WriteStartDocument();
bsonWriter.WriteInt32("_id", this.Id); //10多个个字节,如果用objectId
bsonWriter.WriteString("value", this.Value);//名称如果都改用几个字母可以节省十几个个字节
bsonWriter.WriteString("words", this.WordStr);
bsonWriter.WriteBoolean("isConf", this.IsConflict);
bsonWriter.WriteStartArray("c");
foreach (var item in Chars)
{
BsonSerializer.Serialize(bsonWriter, item.Words.Select(v=>v.IntValue).ToList());
}
bsonWriter.WriteEndArray();
bsonWriter.WriteEndDocument();
}
public void SetDocumentId(object id)
{
throw new NotImplementedException();
}
public object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
//bsonReader.ReadStartDocument();
//this.Id = bsonReader.ReadInt32();
//var value=bsonReader.ReadString("v");
//var wordStr=bsonReader.ReadString("w");
//bsonReader.ReadStartArray();
//var list = new List();
//while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
//{
// var element = BsonSerializer.Deserialize(bsonReader);
// list.Add(element);
//}
//bsonReader.ReadEndArray();
//var isConflict=bsonReader.ReadBoolean("i");
//bsonReader.ReadEndDocument();
if (nominalType != typeof(Sentence))
throw new ArgumentException("不能序列化,因为类型定义不一致");
var doc = BsonDocument.ReadFrom(bsonReader);
this.Id = (Int32)doc["_id"];
this.Value = (string)doc["value"];
this.WordStr = (string)doc["words"];
this.IsConflict = (bool)doc["isConf"];
var list = (BsonArray)doc["c"];
this.Chars = new List();
for (int i = 0; i < list.Count; i++)
{
var ch = new CharObj { Index = i, Sen = this, Words=new List() };
this.Chars.Add(ch);
var words = (BsonArray)list;
foreach (Int32 item in words)
{
var wordObj = new WordObj((UInt32)item);
wordObj.Sen = this;
ch.Words.Add(wordObj);
}
}
foreach (var item in Chars)
{
bsonWriter.WriteStartArray("words");
foreach (var w in item.Words)
bsonWriter.WriteInt32((Int32)w.IntValue);
bsonWriter.WriteEndArray();
}