.NET Core 5下C# 如何将LINQ查询结果转换为指定结构GeoJSON
.NET Core 5 实体转指定结构GeoJSON实现方案
前置说明
首先确认你代码中的Point类型来自.NET生态GIS开发的标准组件NetTopologySuite,以下两种实现方式完全兼容.NET Core 5运行时,输出结构和你给出的示例JSON完全匹配。
实现方式一:零额外依赖的强类型序列化(推荐)
这种方式不需要引入第三方GeoJSON相关包,完全借助.NET Core 5内置的System.Text.Json实现,输出字段可控,不会生成冗余内容。
步骤1:定义和GeoJSON结构严格匹配的强类型
/// <summary> /// GeoJSON最外层FeatureCollection结构 /// </summary> public class GeoFeatureCollection { public string Type { get; set; } = "FeatureCollection"; public List<GeoFeature> Features { get; set; } = new(); } /// <summary> /// 单个要素Feature结构 /// </summary> public class GeoFeature { public int Id { get; set; } public string Type { get; set; } = "Feature"; public GeoPointGeometry Geometry { get; set; } public GeoFeatureProperties Properties { get; set; } } /// <summary> /// 点要素几何结构 /// </summary> public class GeoPointGeometry { public string Type { get; set; } = "Point"; public double[] Coordinates { get; set; } } /// <summary> /// 要素关联的业务属性结构 /// </summary> public class GeoFeatureProperties { public long LandId { get; set; } public long SumSpace { get; set; } public long CLevelId { get; set; } }
步骤2:执行转换逻辑
先修正原LINQ查询的笔误(原代码DBcontext.TLandPointSelect漏了点号,应为DBcontext.TLandPoint.Select),拿到查询结果后执行如下转换:
// 接收之前查询得到的TLandPt列表 var featureCollection = new GeoFeatureCollection(); foreach (var item in TLandPt) { featureCollection.Features.Add(new GeoFeature { // 绑定Feature的id为实体的gid字段 Id = item.gid, Geometry = new GeoPointGeometry { // 直接从Point对象取XY坐标,顺序和示例要求完全匹配 Coordinates = new[] { item.geom.X, item.geom.Y } }, Properties = new GeoFeatureProperties { LandId = item.LandId, SumSpace = item.SumSpace, CLevelId = item.CLevelId } }); } // 用内置序列化器输出,可选开启缩进美化 string resultGeoJson = JsonSerializer.Serialize(featureCollection, new JsonSerializerOptions { WriteIndented = true });
实现方式二:NetTopologySuite生态快速序列化
如果你后续还要处理线、面等其他几何类型,可以安装兼容.NET Core 5版本的NuGet包NetTopologySuite.IO.GeoJSON4STJ(适配System.Text.Json的GeoJSON序列化组件),直接使用组件内置的FeatureCollection、Feature类完成转换,不需要自定义强类型,适合多几何类型的扩展场景,核心逻辑依然是:把实体的gid绑定到Feature的Id属性,业务字段填充到Properties字典,几何对象直接传入即可。
常见踩坑提醒
- 坐标顺序:NetTopologySuite的Point对象默认存储顺序为X(东向坐标)、Y(北向坐标),和你示例中GeoJSON的coordinates顺序完全一致,不需要手动交换坐标值,避免出现坐标偏移问题
- 字段过滤:强类型序列化方式不会把
gid、geom这类不需要的字段写入properties部分,输出结构完全贴合示例要求 - 类型兼容:原实体里
SumSpace字段同时标注了[MaxLength(150)]和long类型,不影响当前的序列化流程,只要查询返回的值为数字类型即可正常输出
内容的提问来源于stack exchange,提问作者r_ab
相关产品推荐
相关产品推荐

