ASP.NET/ EF Core/ NetTopologySuite 使用GeoJSON进行数据传输

以Postgresql为例,首先安装依赖:

dotnet add package NetTopologySuite 
dotnet add package Npgsql.NetTopologySuite 

对于一个Location数据:

[Table("location")]
public class Location 
{
  public string Name {get;set;}
  public NetTopologySuite.Geometries.LineString? Geom {get;set;}
}

以.net6为例,通过在Program.cs中添加GlobalTypeMapper

NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite();

之后需在为自己的DbContext添加如下配置:

builder.Services.AddDbContext<MyDbContext>(options =>
    options
        .UseNpgsql("your-db-connection-string", x => x.UseNetTopologySuite())
);

至此,已完成模型>>PostGIS类型的映射,当写好Controller希望测试新增记录的接口的时候,会发现好像没有一个合适的方法来进行数据传输。

我想偷懒,测试了两种比较通用的明文格式GeoJSON和WKT作为描述:

{
  "Name":"example",
  "Geom":{
    'type': 'LineString',
    'coordinates': [
      [122.483696, 37.833818],
      [122.492237, 37.833378],
      [122.493782, 37.833683]
    ]
   }
}
···
{
  "Name":"example",
  "Geom":"LINESTRING (30 10, 10 30, 40 40)"
}

得到了一样的结果:

Unable to find a constructor to use for type NetTopologySuite.Geometries.LineString

看来Npgsql/NetTopologySuite没有定义隐式的转换,因此需要声明一个JsonConverter来强制执行这一转换,参考这个问题

https://github.com/NetTopologySuite/NetTopologySuite.IO.GeoJSON/issues/17#issuecomment-441620819

我们首先需要添加NetTopologySuite的GeoJSON拓展

dotnet add package NetTopologySuite.IO.GeoJSON

之后添加为空间字段添加JsonConverter:

[Table("location")]
public class Location 
{
  public string Name {get;set;}
  [Newtonsoft.Json.JsonConverter(typeof(NetTopologySuite.IO.Converters.GeometryConverter))]
  public NetTopologySuite.Geometries.LineString? Geom {get;set;}
}

这样,通过下面的Request Body就可以正确的解析出空间字段了。

{
  "Name":"example",
  "Geom":{
    'type': 'LineString',
    'coordinates': [
      [122.483696, 37.833818],
      [122.492237, 37.833378],
      [122.493782, 37.833683]
    ]
   }
}

[HttpPost("line")]
public IActionResult AddLocation([FromBody] Location location)
{
    _myDbContext.Locations.Add(location);
    _myDbContext.SaveChanges();
    return Ok();
}

综上完成了nts-postgis的类型映射,实现了通过GeoJSON的数据传输,但如果使用Swagger UI的话,NTS的Geometry类型的Example Value是一个复杂的结构体,不方便通过Swagger UI调试,至于修改空间字段的Example Value,之后再做补充。

posted @ 2021-11-26 17:32  陈昱行  阅读(951)  评论(0编辑  收藏  举报