skip to Main Content

Hi I have been trying to serialize a polygon to a variable using GeoJSON4STJ for Nettopologysuite. So far deserialization works fine, but I am unable to serialize it. Is there any way to do this?

I have added the following code to the startup file as required

public void ConfigureServices(IServiceCollection services) {
  services.AddControllers()
  .AddJsonOptions(options => {
    options.JsonSerializerOptions.Converters.Add(new NetTopologySuite.IO.Converters.GeoJsonConverterFactory());
  });
}

And I am trying to use the following lin

geoStr = JsonSerializer.Serialize(geometry);

2

Answers


  1. Chosen as BEST ANSWER

    It's been a while but since people are still interested, using GeoJSON4STJ requires setting JsonSerializerOptions for System.Text.Json. This is needed for both serialization and deserialization.

    Example:

    using Microsoft.AspNetCore.Mvc;
    
    _jsonOptions = new JsonOptions();
    _jsonOptions.JsonSerializerOptions.Converters.Add(new NetTopologySuite.IO.Converters.GeoJsonConverterFactory());
    
    var gf = NetTopologySuite.NtsGeometryServices.Instance.CreateGeometryFactory(4326);
    
    // Create a polygon from Aurich over Emden, Leer to Aurich
    Geometry geometry = gf.CreatePolygon(new[] {
        new NetTopologySuite.Geometries.Coordinate(7.5404, 53.4837),
        new NetTopologySuite.Geometries.Coordinate(7.1559, 53.3646),
        new NetTopologySuite.Geometries.Coordinate(7.4550, 53.2476),
        new NetTopologySuite.Geometries.Coordinate(7.5404, 53.4837),
    });
    
    var str = JsonSerializer.Serialize(geometry, _jsonOptions.JsonSerializerOptions);
    Console.WriteLine(str);     
    

    If you don't specifically need NetTopologySuite.IO.GeoJSON4STJ or System.Text.Json and are fine with NetTopologySuite.IO.GeoJSON, the answer of @shage_in_excelsior will serve you just fine.


  2. I know this question is aged and this answer doesn’t quite exactly match your ask but I think it might make your specific request for GeoJSON4STJ unnecessary.

    You can convert   NetTopologySuite   Geometry   directly to GeoJSON using `NetTopologySuite.IO’ as follows:

    using NetTopologySuite.IO;

    var geometryData = <Your NetTopologySuite Geometry data>;
    GeoJsonWriter _geoJsonWriter = new GeoJsonWriter();
    var str = _geoJsonWriter.Write(geometryData);

    This will very simply sidestep your need for GeoJSON4STJ to do the work.

    Hope this helps someone.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search