Home > Blockchain >  Can't serialize GeoJson coordinates in .Net Core controller
Can't serialize GeoJson coordinates in .Net Core controller

Time:05-03

I have a .net 6 API project that exports FeatureCollections. I'm using 'NetTopologySuite.IO.GeoJSON' version 2.0.4, and have a public API call like:

public async Task<IActionResult> ExportGeoJSON()
{
    GeoJSON.Net.Feature.FeatureCollection ret = new GeoJSON.Net.Feature.FeatureCollection();
    const double lat = -73.697913;
    const double lon = 50.659193;
    GeoJSON.Net.Geometry.Position coord = new GeoJSON.Net.Geometry.Position(lat, lon);
    GeoJSON.Net.Geometry.Point pt = new GeoJSON.Net.Geometry.Point(coord);
    GeoJSON.Net.Feature.Feature feat = new GeoJSON.Net.Feature.Feature(pt, null, Guid.NewGuid().ToString());
    ret.Features.Add(feat);
    return Ok(ret);
}

When i call this, i get back only:

{
  "Type": "FeatureCollection",
  "Features": [
    {
      "Type": "Feature",
      "Id": "465f399d-b45c-47ed-b9e6-f395cd86b84b",
      "Geometry": {
        "Type": "Point"
      }
    },...

Ok, i look around and find out about GeoJSON4STJ https://github.com/NetTopologySuite/NetTopologySuite.IO.GeoJSON , so I put that into my Startup:

    services.AddControllers()
        .AddJsonOptions(opts =>
        {
            opts.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;    
            opts.JsonSerializerOptions.PropertyNamingPolicy = null;
            opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());   
            opts.JsonSerializerOptions.Converters.Add(new NetTopologySuite.IO.Converters.GeoJsonConverterFactory());    
        });

and run it again, but no change at all. Exactly the same response. Am i missing something?

CodePudding user response:

It seems that you are mixing libraries. NetTopologySuite.IO.GeoJSON (and NetTopologySuite.IO.GeoJSON4STJ) works with features from NetTopologySuite.Features package not from GeoJSON.Net.

  • Related