我有一个以下面格式存储在Mongo中的文档:
"address" : {
"building" : "469",
"coord" : [
-73.961704,
40.662942
],
"street" : "Flatbush Avenue",
"zipcode" : "11225"
}
我正在使用官方C#Mongo驱动程序与MongoDB实例进行通信。我已经定义了以下POCO类来对应文档:
public class Coordinate
{
public float Lat { get; set; }
public float Long { get; set; }
}
public class Address
{
[BsonElement("street")]
public string Street { get; set; }
[BsonElement("zipcode")]
public string ZipCode { get; set; }
[BsonElement("building")]
public string Building { get; set; }
[BsonElement("coord")]
public Coordinate Coord { get; set; }
}
但我不确定在序列化属性方面需要做些什么,以便将coord BSON数组值反序列化为我创建的Coordinate类。
有什么想法吗?
答案 0 :(得分:1)
您需要创建自定义serializer:
public class MyCustomArraySerializer : SerializerBase<Coordinate>
{
public override Coordinate Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
context.Reader.ReadStartArray();
var lat=context.Reader.ReadDouble();
var lon = context.Reader.ReadDouble();
context.Reader.ReadEndArray();
return new Coordinate() { Long = (float)lon, Lat = (float)lat };
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Coordinate value)
{
context.Writer.WriteStartArray();
context.Writer.WriteDouble(value.Lat);
context.Writer.WriteDouble(value.Long);
context.Writer.WriteEndArray();
}
}
然后在Coord
属性中添加此属性:
public class Address
{
//...
//Add this attribute
[BsonSerializer(typeof(MyCustomArraySerializer))]
public Coordinate Coord { get; set; }
}