NetTopologySuite / NetTopologySuite.IO.GeoJSON

GeoJSON IO module for NTS.
BSD 3-Clause "New" or "Revised" License
111 stars 46 forks source link

System.Text.Json: Example of string or file conversion #74

Closed alex3305 closed 3 years ago

alex3305 commented 3 years ago

Is there any example or documentation on how to convert to and from a FeatureCollection with the new System.Text.Json library?

alex3305 commented 3 years ago

After a while of trial and error I figured out how to do deserialization of GeoJSON easily. Example code:

using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using NetTopologySuite.Features;
using NetTopologySuite.IO.Converters;

public class GeoJsonSerializer
{
    public static JsonSerializerOptions DefaultSerializerOptions
    {
        get
        {
            var options = new JsonSerializerOptions {ReadCommentHandling = JsonCommentHandling.Skip};
            options.Converters.Add(new GeoJsonConverterFactory());

            return options;
        }
    }

    public static void RemoveAllProperties(IFeature feature)
    {
        // Just replace the AttributesTable with a new one instead of deleting all properties
        // because the STJ-serialized Feature has a read-only AttributesTable. 
        feature.Attributes = new AttributesTable();
    }

    public static async Task<FeatureCollection> DeserializeGeoJson(string geojson)
    {
        await using var ms = new MemoryStream(Encoding.UTF8.GetBytes(geojson));
        return await Deserialize<FeatureCollection>(ms);
    }

    private static async Task<T> Deserialize<T>(Stream input)
    {
        return await JsonSerializer.DeserializeAsync<T>(input, DefaultSerializerOptions);
    }
}