我需要从mongodb中提取数据,但这些数据在坐标上不同,我可以创建一个基本子类结构并将其POST到mongodb,但坐标不属于GET操作。
public class Geometry
{
public string type { get; set; }
}
public class GeoPoly:Geometry
{
public double[][][] coordinates { get; set; }
}
public class GeoMultipoly : Geometry
{
public double[][][][] coordinates { get; set; }
}
我该怎么做呢
- 序列化约定应该改变吗?如何改变
- 基-子类结构适合这个问题吗?
数据库条目:
{
"type": "Polygon",
"coordinates": [
[
[
[
51.263632,
60.962938
],
[
30.884274,
20.065517
],
[
68.832044,
14.362602
],
[
51.263632,
60.962938
]
]
]
]
},
{
"type": "MultiPolygon",
"coordinates": [
[
[
[
43.182162,
64.042209
],
[
14.721334,
22.358269
],
[
51.263632,
17.738761
],
[
43.182162,
64.042209
]
]
],
[
[
[
55.831419,
51.446822
],
[
65.66973,
20.065517
],
[
97.64424,
37.509124
],
[
55.831419,
51.446822
]
]
]
]
}
我不确定这是最好的主意,但newtonsoft
和json.net
支持用$type
序列化和反序列化。
项目将被保存在DB中,并带有它的完整类标识符。
你可以在这里查看
一个例子:
// {
// "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests",
// "FullName": "Steve Stockholder",
// "Businesses": {
// "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib",
// "$values": [
// {
// "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
// "Stars": 4,
// "Name": "Hudson Hotel"
// }
// ]
// }
// }
要使用它,请查看newtonsoft文档。
用法示例:
Stockholder stockholder = new Stockholder
{
FullName = "Steve Stockholder",
Businesses = new List<Business>
{
new Hotel
{
Name = "Hudson Hotel",
Stars = 4
}
}
};
string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
这个JSON右类要做的是:
public class Rootobject
{
public string type { get; set; }
public float[][][][] coordinates { get; set; }
}
对于geoopoly和geommultiply,实际上是相同的。您可以分两步处理:
- 获取列表id Rootobject (list)
switch(g.type)
{
case "GeoPoly":
result.Add(new GeoPoly
{
type = g.type;
coordinates = g.coordinates
});
break;
case "GeoMultipoly":
result.Add(new GeoMultipoly
{
type = g.type;
coordinates = g.coordinates
});
break;
default:
continue;
}
最后的结果列表将有一个右类型的几何类型列表。