c# - 将 DataTable 序列化为 GeoJSON 对象?
问题描述
我一直无法将数据表转换为 GeoJSON 对象。
数据表如下所示:
Name Status imageUrl lat lon
Joe Dev markers/Dev.svg 34.21092 -77.59384
Mary Dev markers/Dev.svg 32.49323 -78.43144
GeoJSON 应如下所示:
{
"type" : "FeatureCollection",
"features" : [
{
"type" : "Feature",
"properties" : {
"Name " : "Joe",
"Status" : "Dev",
"imageUrl" : "markers/Dev.svg",
"lat" : 34.21092,
"lon" : -77.59384
},
"geometry" : {
"type" : "Point",
"coordinates" : [ -77.59384, 34.21092 ]
}
},
{
"type" : "Feature",
"properties" : {
"Name " : "Mary",
"Status" : "Dev",
"imageUrl" : "markers/Dev.svg",
"lat" : 32.49323,
"lon" : -78.43144
},
"geometry" : {
"type" : "Point",
"coordinates" : [ -78.43144, 32.49323 ]
}
}
]
}
我一直在到处寻找,但还没有找到解决方案。我一直在使用 NewtonSoft 将 a 序列化为DataTable
对象JSON
,但 GeoJSON 是一种更复杂的格式。
最困难的部分是必须在其他类别中包含类别。无论如何,这是我尝试过的:
使用Newtonsoft
,我能够将数据表转换为 JSON。显然,这不是解决方案:
string callback = JsonConvert.SerializeObject(dataTable);
[] resultBytes = Encoding.UTF8.GetBytes(callback);
return new System.IO.MemoryStream(resultBytes);
向前迈出一步,这是我尝试添加一些 geojson 属性的内容:
var envelope = new
{
type = "FeatureCollection",
features = result.Tables[0]
};
string callback = JsonConvert.SerializeObject(envelope);
byte[] resultBytes = Encoding.UTF8.GetBytes(callback);
这会返回更接近的内容,但仍然缺少{"type": "Feature", "properties"
每个数组中的内容。
最后,我在这里发布了一个类似的问题,它非常有帮助,但是它以实际json
而不是作为参数datatable
,这带来了许多其他问题,主要是这里的这个。
所以我决定从头开始并发布一个问题,询问我如何获取我的源(常规数据表)并将其转换为GeoJson
像上面这样的对象。
任何帮助表示赞赏。
解决方案
您需要将dataTable
记录映射到多维对象结构中。我建议使用 LinQ 这样做。
要迭代 dataTable,请使用.AsEnumerable()
dataTable 对象。
解决方案:创建一个转换为 GeoJSON 字符串convert
的函数。DataTable
System.Linq
namespace
确保在您的.cs
文件中导入
public static string DataTableToGeoJSONString(DataTable dataTable)
{
var envelope = new
{
type = "FeatureCollection",
features = dataTable.AsEnumerable().Select(record => new {
type = "Feature",
properties = new
{
Name = Convert.ToString(record["Name"]),
Status = Convert.ToString(record["Status"]),
imageUrl = Convert.ToString(record["imageUrl"]),
lat = Convert.ToDecimal(record["lat"]),
lon = Convert.ToDecimal(record["lon"])
},
geometry = new
{
type = "Point",
coordinates = new[] {
Convert.ToDecimal(record["lon"]),
Convert.ToDecimal(record["lat"])
}
}
}).ToArray()
};
return JsonConvert.SerializeObject(envelope);
}
只需从中取出 JSON 字符串
string geoJson = DataTableToGeoJSONString(dataTable);
请注意,此代码示例使用匿名类new {}
。它有效,但我建议使用您必须创建的强类型类。
这应该以预期的 GeoJSON 格式序列化。
推荐阅读
- python - 定义一个函数并将其用于python中的多个文件或模块
- lodash - Lodash 创建自定义函数的方式
- php - 数据库未连接到生产环境
- python - 获取列中某个唯一值的数量
- matlab - 使用当前时间保存工作区。MATLAB
- .htaccess - htaccess中的重写和重定向url问题
- java - Hive 选择问题:java.lang.IncompatibleClassChangeError
- visual-studio - 替换 Visual Studio 菜单中的默认移动键
- c++ - 此序列背后的逻辑已构建,但出现问题?
- java - 自定义溢出菜单在 android API 21 和 23+ 中不会给出相同的结果