.NET Core将GeoJson存入PostGIS时出现无效GeoJson表示错误
解决PostGIS "invalid GeoJson representation" 错误
问题重现
- 读取GeoJSON文件并解析为FeatureCollection:
// parse the GeoJSON string into a FeatureCollection object var featureCollection = geoJsonReader.Read<FeatureCollection>(geoJsonString);
- 筛选目标Feature:
IFeature relatedGeoJsonFeature = new Feature(); foreach (var feature in featureCollection) { // get the properties of the feature var properties = feature.Attributes; var id = properties["id"] as string; if (id == $"{element.type + "/" + element.id}") { relatedGeoJsonFeature = feature; } }
- 将Feature转为JSON字符串:
var writer = new GeoJsonWriter(); var jsonString = writer.Write(relatedGeoJsonFeature);
- 尝试存入PostGIS:
INSERT INTO public."Cities" ("geometry","jsonGeo","parentType","parentId") values (ST_GeomFromGeoJSON(@geometry), @jsonGeo::text::jsonb,@parentType,@parentId);
command.Parameters.AddWithValue("@geometry", NpgsqlTypes.NpgsqlDbType.Text, jsonString);
执行后抛出错误:
Npgsql.PostgresException (0x80004005): XX000: invalid GeoJson representation at Npgsql.Internal.NpgsqlConnector.ReadMessageLong(Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage) at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken) at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken) at Npgsql.NpgsqlDataReader.NextResult() at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlCommand.ExecuteNonQuery() at EazyCityCA.Services.CityStoreClass.Run() in /Users/alt/Projects/MyProjects/eazy_city/EazyCityCore/EazyCityCA/Services/CityStoreClass.cs:line 108 Exception data: Severity: ERROR SqlState: XX000 MessageText: invalid GeoJson representation File: lwgeom_pg.c Line: 340 Routine: pg_error XX000: invalid GeoJson representation
核心原因
PostGIS的ST_GeomFromGeoJSON函数仅接受GeoJSON Geometry类型对象(如Point、Polygon、LineString等),但你传入的是完整的Feature对象(包含properties、geometry等字段的JSON结构),不符合函数的输入要求,导致解析失败。
解决方法
方法1:提取Feature中的Geometry对象再序列化
修改代码,只提取Feature的Geometry部分转为JSON字符串传入参数:
// 提取Feature中的Geometry对象 var geometry = relatedGeoJsonFeature.Geometry; // 仅序列化Geometry部分 var geometryJson = writer.Write(geometry); // 传入参数 command.Parameters.AddWithValue("@geometry", NpgsqlTypes.NpgsqlDbType.Text, geometryJson);
方法2:直接使用Npgsql的空间类型支持
若使用的Npgsql版本支持空间类型,可直接传入Geometry对象,无需手动序列化:
- 确保已安装
Npgsql.NetTopologySuite包 - 修改代码:
// 提取Geometry并设置空间参考(示例为WGS84,EPSG:4326) var geometry = relatedGeoJsonFeature.Geometry; geometry.SRID = 4326; // 直接传入Geometry对象,Npgsql会自动处理序列化 command.Parameters.AddWithValue("@geometry", geometry);
对应的SQL简化为:
INSERT INTO public."Cities" ("geometry","jsonGeo","parentType","parentId") values (@geometry, @jsonGeo::text::jsonb,@parentType,@parentId);
额外排查步骤
- 验证输出的JSON格式:打印
jsonString或geometryJson,手动检查是否符合GeoJSON规范(确保是标准的Geometry结构,而非完整Feature)。 - 检查空间参考系:若Geometry未设置SRID,PostGIS可能无法识别,建议显式设置常用的参考系(如EPSG:4326)。
- 确认PostGIS版本:较旧的PostGIS版本对GeoJSON的支持可能有局限性,尽量使用最新稳定版。
内容的提问来源于stack exchange,提问作者Cyrus the Great
相关产品推荐
相关产品推荐

