简体   繁体   English

将位置坐标的Mongo BSON数组反序列化为自定义C#类

[英]Deserialize Mongo BSON array of location coordinates to custom C# class

I have a document stored in Mongo of the below format: 我在Mongo中存储了以下格式的文档:

"address" : {
    "building" : "469",
    "coord" : [ 
        -73.961704, 
        40.662942
    ],
    "street" : "Flatbush Avenue",
    "zipcode" : "11225"
}

I am using the official C# Mongo Driver to communicate with The MongoDB instance. 我正在使用官方的C#Mongo驱动程序与MongoDB实例进行通信。 I have defined the following POCO classes to correspond to the document: 我定义了以下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; }
}

But I am not certain what has to be done in terms of the serialization attributes so that the coord BSON array values are deserialized into the Coordinate class that I have created. 但是我不确定在序列化属性方面必须做什么,以便将coord BSON数组值反序列化为我创建的Coordinate类。

Any ideas? 有任何想法吗?

You need to create a custom 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();
    }
}

And then add this attribute on Coord property: 然后在Coord属性上添加此属性:

public class Address
{
    //...
    //Add this attribute
    [BsonSerializer(typeof(MyCustomArraySerializer))]
    public Coordinate Coord { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM